如何将两个过程组合成一个?

只是想知道是否有一个语法快捷方式,用于获取两个proc并加入它们,以便将一个的输出传递给另一个,相当于:

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

当使用method(:abc).to_proc:xyz.to_proc类的东西时,这会派上用场

更多的糖, 在生产代码中并不是真正推荐的

 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 
 a = Proc.new { |x| x + 1 } b = Proc.new { |x| x * 10 } c = Proc.new { |x| b.call(a.call(x)) } 

你可以像这样创建一个联合操作

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

然后你可以像这样使用它

  a = -> (x) { x + 1 } b = -> (x) { x * 10 } c = -> (x) {bind(x).union(a).union(b).call} 
Interesting Posts