liveBook · Manning

Tap combinator

As explained in The Well-Grounded Rubyist, Fourth Edition

tap yields its receiver to a supplied block and then returns that receiver unchanged as the method result.

Ruby's tap method yields its receiver to a block, then returns that same receiver unchanged. This makes it useful for observing or modifying an object without interrupting a method chain. section 13.2.1

Inspect, then continue chaining

"Hello".tap { puts it.upcase }.reverse prints HELLO and evaluates to "olleH": the block observes the string, while reverse receives the original receiver. section 13.2.1

Use tap carefully when working with methods whose return values carry control-flow or chaining meaning:

  • A bang method such as gsub! may return nil when no change occurs, but tap still returns the string. section 13.2.1
  • Tap can clarify intent, but mixing in-place operations with methods returning copies can make longer chains harder to reason about. section 13.2.1
>> "Hello".tap { puts it.upcase }.reverse
HELLO
=> "olleH"

Runnable irb example showing tap's block result and unchanged receiver. section 13.2.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains yielding, unchanged return, chaining, and bang-method edge cases, but stops short of implementation internals.
Examples
Demonstrates printing an uppercased string, reversing after tap, and applying gsub! inside the block.
What you can do after
Apply it via Ruby method chains to inspect or modify receivers without replacing the chain's value.
How it connects
Connects tap with blocks, receivers, bang methods, in-place operations, and method chaining.

Also explained in

Compare how 2 books explain tap combinator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.