Search code examples
ruby

advantage of tap method in ruby


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 = "foobar"
  u.save!
end

My question is what exactly is the benefit or advantage of using tap? Couldn't I just do:

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

or better yet:

user = User.create! username: "foobar"

Solution

  • 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.