Mutant version of the tap - or a way of expressing pipes?

tapgives selfthe block passed to it and returns selfunchanged. I often wish there was a version tapthat returned the return value of the block, not self. For example:

[1,2].inject(:+).tap {|x| x * 3} #=> returns 3, but I want 9

Is there a built-in method that will do this?

A typical solution - create a temporary local var to store the output [1,2].inject(:+)and multiply it by 3 - it seems kludgy.

+2
source share
3 answers

There is no built-in method for this, but you can add Kernel#ergofrom Ruby Facets :

"a".ergo.upcase #=> "A"
nil.ergo.foobar #=> nil

"a".ergo { |o| o.upcase } #=> "A"
nil.ergo { |o| o.foobar } #=> nil

This is similar to #tap, but #tap gives self and returns self, where when #ergo returns self, but returns a result.

+3
source

.

class Object
  def my_tap
    return yield self if block_given?
    self
  end
end

[1,2].inject(:+).my_tap {|x| x * 3}
=> 9
+2
0
source

Source: https://habr.com/ru/post/1620596/


All Articles