advantage of tap method in ruby

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

    There could be number of uses and places where we may be able to use tap. So far I have only found following 2 uses of tap.

    1) The primary purpose of this method is to tap into a method chain, in order to perform operations on intermediate results within the chain. i.e

    (1..10).tap { |x| puts "original: #{x.inspect}" }.to_a.
        tap    { |x| puts "array: #{x.inspect}" }.
        select { |x| x%2 == 0 }.
        tap    { |x| puts "evens: #{x.inspect}" }.
        map    { |x| x*x }.
        tap    { |x| puts "squares: #{x.inspect}" }
    

    2) Did you ever find yourself calling a method on some object, and the return value not being what you wanted it to? Maybe you wanted to add an arbitrary value to a set of parameters stored in a hash. You update it with Hash.[], but you get back bar instead of the params hash, so you have to return it explicitly. i.e

    def update_params(params)
      params[:foo] = 'bar'
      params
    end
    

    In order to overcome this situation here, tap method comes into play. Just call it on the object, then pass tap a block with the code that you wanted to run. The object will be yielded to the block, then be returned. i.e

    def update_params(params)
      params.tap {|p| p[:foo] = 'bar' }
    end
    

    There are dozens of other use cases, try finding them yourself :)

    Source:
    1) API Dock Object tap
    2) five-ruby-methods-you-should-be-using

提交回复
热议问题