advantage of tap method in ruby

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

    There is a tool called flog that measures how difficult it is to read a method. "The higher the score, the more pain the code is in."

    def with_tap
      user = User.new.tap do |u|
        u.username = "foobar"
        u.save!
      end
    end
    
    def without_tap
      user = User.new
      user.username = "foobar"
      user.save!
    end
    
    def using_create
      user = User.create! username: "foobar"
    end
    

    and according on flog's result the method with tap is the most difficult to read (and I agree with it)

     4.5: main#with_tap                    temp.rb:1-4
     2.4:   assignment
     1.3:   save!
     1.3:   new
     1.1:   branch
     1.1:   tap
    
     3.1: main#without_tap                 temp.rb:8-11
     2.2:   assignment
     1.1:   new
     1.1:   save!
    
     1.6: main#using_create                temp.rb:14-16
     1.1:   assignment
     1.1:   create!
    

提交回复
热议问题