Ruby 1.9 gets handy new method Object#tap

Posted on
Tags: ruby, tap, helpers, rails

Via I learned that Ruby 1.9 will sport a new Object method called tap, which is something I’ve been hoping for.

What’s tap? It’s a helper for call chaining. It passes its object into the given block and, after the block finishes, returns the object:

The benefit is that tap always returns the object it’s called on, even if the block returns some other result. Thus you can insert a tap block into the middle of an existing method pipeline without breaking the flow. MenTaLguY has some nifty examples of other things you can do with tap.

Fans of Ruby on Rails may recognize tap as similar to RoR’s own returning helper.

Looks like Ruby 1.9 is going to be extra cool for a number of reasons.