advantage of tap method in ruby

后端 未结 19 1010
天命终不由人
天命终不由人 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:42

    You can make your codes more modular using tap, and can achieve a better management of local variables. For example, in the following code, you don't need to assign a local variable to the newly created object, in the scope of the method. Note that the block variable, u, is scoped within the block. It is actually one of the beauties of ruby code.

    def a_method
      ...
      name = "foobar"
      ...
      return User.new.tap do |u|
        u.username = name
        u.save!
      end
    end
    

提交回复
热议问题