Ruby 1.9 gets handy new method Object#tap
Posted by Tom Moertel Wed, 07 Feb 2007 17:08:00 GMT
Via
eigenclass.org
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:
an_object.tap do |o|
# do stuff with an_object, which is in o
end # ===> an_objectThe 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 pipleline 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.
readers


MentalGuy doesn’t just have nifty examples – he invented the technique!
I’ve been using it for awhile now, ever since I read his post.