advantage of tap method in ruby

后端 未结 19 1047
天命终不由人
天命终不由人 2020-12-22 16:50

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 = \         


        
19条回答
  •  爱一瞬间的悲伤
    2020-12-22 17:52

    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.

提交回复
热议问题