You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby中传递Proc与方法:compose返回Proc的参数传递机制疑问

How the Argument 5 Travels Through doubleThenSquare.call(5)

First, let's recap your code for context:

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)

Let's break down exactly how the argument 5 flows through your code step by step:

Step 1: What compose actually creates

When you run compose(doubleIt, squareIt), the method doesn't execute any logic right away—it returns a new, anonymous Proc. This Proc is basically a wrapper that defines a sequence: when you call it with an argument, it will first run the first passed Proc (doubleIt), then feed that result into the second passed Proc (squareIt).

Step 2: Tracing doubleThenSquare.call(5)

When you call doubleThenSquare.call(5), here's the play-by-play:

  1. The composed Proc receives 5 as its input parameter (the x in its block).
  2. It first runs proc1.call(x)—since proc1 is doubleIt, this becomes doubleIt.call(5). The doubleIt Proc takes 5, computes 5 + 5, and returns 10.
  3. Next, it takes that 10 and passes it to proc2.call()—since proc2 is squareIt, this becomes squareIt.call(10). The squareIt Proc takes 10, computes 10 * 10, and returns 100.
  4. Finally, the composed Proc returns 100 as the result of doubleThenSquare.call(5).

Quick comparison: squareThenDouble.call(5)

To drive the point home, here's how the argument flows for the other composed Proc:

  1. The composed Proc gets 5 as input.
  2. Runs squareIt.call(5) first, which returns 25.
  3. Feeds 25 into doubleIt.call(25), which returns 50.
  4. So squareThenDouble.call(5) outputs 50.

The core idea here is that compose builds a chain of operations: the output of the first Proc becomes the input of the second, and the argument you pass to the composed Proc starts at the very beginning of that chain.


内容的提问来源于stack exchange,提问作者msmith1114

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:15:33