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.

Leave a Comment