普通の tap の使い方

tap is a method for eavesdropping on any portion of an expression.

Suppose there is a bug in the following code:

data.foo.bar.baz

It could be that data is not what you expect it to be, or one (or more) of the methods foo, bar and baz doesn't work as it should.

You can check these possibilities by catching data at points where the data comes out from the previous operation and goes into the next. In this case, these points are represented by the dot operator.

Using Kernel#p, you could do this:

(p data).foo.bar.baz
(p data.foo).bar.baz
(p data.foo.bar).baz

But this requires you to insert code at two places. Since these changes are likely to be undone once the bug is gone, you might want to achieve the same effect with only one place to change. tap allows you to do just that.

data.tap{|x| p x}.foo.bar.baz
data.foo.tap{|x| p x}.bar.baz
data.foo.bar.tap{|x| p x}.baz

Note that tap evaluates to its receiver no matter what the block given to it returns. true.tap { false } still evaluates to true.