Today I wanted to talk about
#tap, an addition to Ruby in versions >= 1.9, and how I’ve been using and seeing it used lately.
The feature is coded like so:
So, in Ruby:
So that looks pretty simple, it just allows you do do something with an object inside of a block, and always have that block return the object itself.
#tap was created for tapping into method chains, so code like this:
can be turned into (without modifying the contract of
Where has it gone wrong?
Some early blog posts talking about tap focused on its use for inserting calls to
putsinto code without modifying behavior:
This isn’t a great use, not only because it involves debugging your code solely by means of output (instead of a
debugger), but also because
#tap is so much cooler an idea than just a mechanism for inserting temporary code.
Why I like it:
In additional to the tapping behavior described in the first section, here are some other uses I’m seeing / using:
Assigning a property to an object
Especially useful when assigning a single attribute
Ignoring method return
Useful when wanting to call a single method on an object and keep working with the object afterwards:
Using in-place operations chained
A lot of times, we expand logic in order to use in-place methods like
reverse!, but look:
Just like anything else, don’t overuse
#tap just for kicks. Its tempting to tap everything, but it definitely can make code less readable if used inappropriately. That being said, its a great addition to a Rubyist’s sugar toolkit. Give it a shot!