advantage of tap method in ruby

When readers encounter:

user = User.new
user.username = "foobar"
user.save!

they would have to follow all the three lines and then recognize that it is just creating an instance named user.

If it were:

user = User.new.tap do |u|
  u.username = "foobar"
  u.save!
end

then that would be immediately clear. A reader would not have to read what is inside the block to know that an instance user is created.


Another case to use tap is to make manipulation on object before returning it.

So instead of this:

def some_method
  ...
  some_object.serialize
  some_object
end

we can save extra line:

def some_method
  ...
  some_object.tap{ |o| o.serialize }
end

In some situation this technique can save more then one line and make code more compact.

Tags:

Ruby