9

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

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

method(:abc).to_proc这在处理类似的事情时会派上用场:xyz.to_proc

4

4 回答 4

8

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

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
于 2013-05-28T19:32:57.003 回答
2

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

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}
于 2013-05-29T06:15:08.053 回答
2
a = Proc.new { |x| x + 1 }
b = Proc.new { |x| x * 10 }
c = Proc.new { |x| b.call(a.call(x)) }
于 2013-05-28T19:26:31.623 回答
1

更新的答案。Proc 组合在 Ruby 2.6 中已经可用。有两种方法<<>>,在组合顺序上有所不同。所以现在你可以做

##ruby2.6
a = ->(x) { x + 1 }
b = ->(x) { x * 10 }
c = a >> b
c.call(1) #=> 20
于 2019-06-15T09:32:28.277 回答