I was just reading a blog article and noticed that the author used tap
in a snippet something like:
user = User.new.tap do |u|
u.username = \
You're right: the use of tap
in your example is kind of pointless and probably less clean than your alternatives.
As Rebitzele notes, tap
is just a convenience method, often used to create a shorter reference to the current object.
One good use case for tap
is for debugging: you can modify the object, print the current state, then continue modifying the object in the same block. See here for example: http://moonbase.rydia.net/mental/blog/programming/eavesdropping-on-expressions.
I occasionally like to use tap
inside methods to conditionally return early while returning the current object otherwise.