advantage of tap method in ruby

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

    A variation on @sawa's answer:

    As already noted, using tap helps figuring out the intent of your code (while not necessarily making it more compact).

    The following two functions are equally long, but in the first one you have to read through the end to figure out why I initialized an empty Hash at the beginning.

    def tapping1
      # setting up a hash
      h = {}
      # working on it
      h[:one] = 1
      h[:two] = 2
      # returning the hash
      h
    end
    

    Here, on the other hand, you know right from the start that the hash being initialized will be the block's output (and, in this case, the function's return value).

    def tapping2
      # a hash will be returned at the end of this block;
      # all work will occur inside
      Hash.new.tap do |h|
        h[:one] = 1
        h[:two] = 2
      end
    end
    

提交回复
热议问题