DEV Community

Patrick Wendo
Patrick Wendo

Posted on

Today I Learned about the tap method in Ruby

Tell me if this seems familiar

user = User.find(1)
user.age = 11
user.save
Enter fullscreen mode Exit fullscreen mode

This is a common pattern that I use often. Turns out the creators of Ruby saw this was a recurring pattern and decided to come up with the tap method. According to the Docs: The Tap method yields self to the block, and then returns self. The primary purpose of this method is to “tap into” a method chain, in order to perform operations on intermediate results within the chain.

What this means is that, the code block above can be simplified to

User.find(1).tap do |user|
    user.age = 10
    user.save
end
Enter fullscreen mode Exit fullscreen mode

Tap will take the object it is called upon and use it in the block that follows.

Discussion (4)

Collapse
citizen428 profile image
Michael Kohl • Edited on

I have the following in my ~/.pryrc (and ~/.irbrc):

class Object
  def d
    tap { |o| puts o }
  end
end
Enter fullscreen mode Exit fullscreen mode

This makes it easy to debug message chains in the REPL, you just add a call to d in between the other calls.

Collapse
w3ndo profile image
Patrick Wendo Author

This is interesting for 2 reasons,

  1. I didn't know you could edit your ~/.irbrc Seems very useful. Will have to try that after work today.
  2. When you say make a call to d, you mean like if we have an Object user, you'd call user.d and it would return the user? Isn't that circular? Or am I not getting it? Could you explain?
Collapse
citizen428 profile image
Michael Kohl

Re 1: Both my .irbrc and .pryrc are on Github if you need some inspiration. If you work with Rails you may also want to look into adding a project specific .pryrc

Re 2: I mentioned I use it for debugging message chains or to illustrate to people which transformations happen in the intermediate steps:

>> "foo".upcase.d.reverse.d.capitalize
FOO
OOF
"Oof"
Enter fullscreen mode Exit fullscreen mode

Here the first two lines are the printed output from .d and "Oof" is the return value of the message chain.

Thread Thread
w3ndo profile image
Patrick Wendo Author

I'll definitely check them out.

This is pretty useful for debugging.