How to combine two procs into one?

It's just interesting if there is a syntax shortcut for accepting two procs and attaching them, so that the output of one of them is passed to the other, which is equivalent:

a = ->(x) { x + 1 } b = ->(x) { x * 10 } c = ->(x) { b.( a.( x ) ) } 

This comes in handy when working with things like method(:abc).to_proc and :xyz.to_proc

+8
ruby function-composition
source share
4 answers

More sugar, not recommended in production code

 class Proc def *(other) ->(*args) { self[*other[*args]] } end end a = ->(x){x+1} b = ->(x){x*10} c = b*a c.call(1) #=> 20 
+7
source share
 a = Proc.new { |x| x + 1 } b = Proc.new { |x| x * 10 } c = Proc.new { |x| b.call(a.call(x)) } 
+2
source share

you can create such a join operation

 class Proc def union p proc {p.call(self.call)} end end def bind v proc { v} end 

then you can use it like that

  a = -> (x) { x + 1 } b = -> (x) { x * 10 } c = -> (x) {bind(x).union(a).union(b).call} 
+2
source share

Updated answer. Proc is now available in Ruby 2.6. There are two methods << and >> that differ in composition order. So now you can do

 ##ruby2.6 a = ->(x) { x + 1 } b = ->(x) { x * 10 } c = a >> b c.call(1) #=> 20 
0
source share

All Articles