Today I Learned about the tap method in Ruby

w3ndo

Patrick Wendo

Posted on May 26, 2022

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.

💖 💪 🙅 🚩
w3ndo
Patrick Wendo

Posted on May 26, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related