advantage of tap method in ruby

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

    You're right: the use of tap in your example is kind of pointless and probably less clean than your alternatives.

    As Rebitzele notes, tap is just a convenience method, often used to create a shorter reference to the current object.

    One good use case for tap is for debugging: you can modify the object, print the current state, then continue modifying the object in the same block. See here for example: http://moonbase.rydia.net/mental/blog/programming/eavesdropping-on-expressions.

    I occasionally like to use tap inside methods to conditionally return early while returning the current object otherwise.

提交回复
热议问题