Ruby中传递Proc与方法:compose返回Proc的参数传递机制疑问
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:
- The composed Proc receives
5as its input parameter (thexin its block). - It first runs
proc1.call(x)—sinceproc1isdoubleIt, this becomesdoubleIt.call(5). ThedoubleItProc takes5, computes5 + 5, and returns10. - Next, it takes that
10and passes it toproc2.call()—sinceproc2issquareIt, this becomessquareIt.call(10). ThesquareItProc takes10, computes10 * 10, and returns100. - Finally, the composed Proc returns
100as the result ofdoubleThenSquare.call(5).
Quick comparison: squareThenDouble.call(5)
To drive the point home, here's how the argument flows for the other composed Proc:
- The composed Proc gets
5as input. - Runs
squareIt.call(5)first, which returns25. - Feeds
25intodoubleIt.call(25), which returns50. - So
squareThenDouble.call(5)outputs50.
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

