传递过程和方法

Passing procs and methods

我遇到了这段代码:

squareIt = Proc.new do |x|
  x * x
end

doubleIt = Proc.new do |x|
  x + x
end

def compose proc1, proc2
  Proc.new do |x|
    proc2.call(proc1.call(x))
  end
end

doubleThenSquare = compose(doubleIt, squareIt)
squareThenDouble = compose(squareIt, doubleIt)

doubleThenSquare.call(5)
squareThenDouble.call(5)

doubleThenSquare5 调用。 doubleThenSquare 等于 compose 的 return 值,它有两个参数 doubleItsquareIt 传递。

我不明白 5 是如何传递到不同的过程中的 Proc.new do |x|。它如何知道每种情况下的 x 是什么?

让我们逐步完成它。

doubleIt = Proc.new do |x|
  x + x
end
  #=> #<Proc:0x00000002326e08@(irb):1429>

squareIt = Proc.new do |x|
  x * x
end
  #=> #<Proc:0x00000002928bf8@(irb):1433>

proc1 = doubleIt
proc2 = squareIt

compose returns 过程 proc3.

proc3 = Proc.new do |x|
    proc2.call(proc1.call(x))
end
  #=> #<Proc:0x000000028e7608@(irb):1445>

proc3.call(x)的执行方式与

相同
proc3_method(x)

哪里

def proc3_method(x)
  y = proc1.call(x)
  proc2.call(y)
end

x = 5,

y = proc1.call(5)
  #=> 10
proc2.call(10)
  #=> 100

proc3_method(5) 因此 returns 100proc3.call(5).

也是如此