advantage of tap method in ruby

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

    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.

提交回复
热议问题