Tell me if this seems familiar
user = User.find(1)
user.age = 11
user.save
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
Tap will take the object it is called upon and use it in the block that follows.
Top comments (3)
This is interesting for 2 reasons,
user.d
and it would return the user? Isn't that circular? Or am I not getting it? Could you explain?I'll definitely check them out.
This is pretty useful for debugging.
I think it is debatable whether the code in the post User.find(1).tap do ... is actually a simplification. There is not so much difference to the original version. The only difference I see: the scope of the user variable is more local.
I looked at the linked Doc. The example there shows how to use tap to add print statements for debugging. So maybe this is the more intended purpose of the method: Allowing a quick and temporary code modification that will be removed later.
I think for the example in the blog post I might need to see a longer method with more context around the code in the post to convince me that this is useful. Not sure.