advantage of tap method in ruby

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

    I would say that there is no advantage to using tap. The only potential benefit, as @sawa points out is, and I quote: "A reader would not have to read what is inside the block to know that an instance user is created." However, at that point the argument can be made that if you're doing non-simplistic record creation logic, your intent would be better communicated by extracting that logic into its own method.

    I hold to the opinion that tap is an unnecessary burden on the readability of the code, and could be done without, or substituted with a better technique, like Extract Method.

    While tap is a convenience method, it's also personal preference. Give tap a try. Then write some code without using tap, see if you like one way over another.

提交回复
热议问题