advantage of tap method in ruby

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

    In the world where functional programming pattern is becoming a best practice (https://maryrosecook.com/blog/post/a-practical-introduction-to-functional-programming), you can see tap, as a map on a single value, indeed, to modify your data on a transformation chain.

    transformed_array = array.map(&:first_transformation).map(&:second_transformation)
    
    transformed_value = item.tap(&:first_transformation).tap(&:second_transformation)
    

    No need to declare item multiple times here.

提交回复
热议问题