advantage of tap method in ruby

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

    Using tap, as the blogger did, is simply a convenience method. It may have been overkill in your example, but in cases where you'd want to do a bunch of things with the user, tap can arguably provide a cleaner looking interface. So, perhaps it may be better in an example as follows:

    user = User.new.tap do |u|
      u.build_profile
      u.process_credit_card
      u.ship_out_item
      u.send_email_confirmation
      u.blahblahyougetmypoint
    end
    

    Using the above makes it easy to quickly see that all those methods are grouped together in that they all refer to the same object (the user in this example). The alternative would be:

    user = User.new
    user.build_profile
    user.process_credit_card
    user.ship_out_item
    user.send_email_confirmation
    user.blahblahyougetmypoint
    

    Again, this is debatable - but the case can be made that the second version looks a little messier, and takes a little more human parsing to see that all the methods are being called on the same object.

提交回复
热议问题