0
0
Rubyprogramming~10 mins

Proc composition in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Proc composition
Define Proc A
Define Proc B
Compose Proc C = B after A
Call Proc C with input
Proc A processes input
Proc B processes Proc A output
Return final result
We define two Procs, then create a new Proc by composing them. Calling the composed Proc runs the first, then passes its output to the second.
Execution Sample
Ruby
a = Proc.new { |x| x + 2 }
b = Proc.new { |y| y * 3 }
c = Proc.new { |z| b.call(a.call(z)) }
result = c.call(4)
puts result
This code composes two Procs: adds 2, then multiplies by 3, and calls the composition with 4.
Execution Table
StepActionInputProc CalledOutputNotes
1Call c.call(4)4c?Start composition call
2Inside c: call a.call(4)4a6a adds 2 to 4
3Inside c: call b.call(6)6b18b multiplies 6 by 3
4Return from c.call(4)4c18Final result is 18
💡 Finished composition: output 18 returned after running a then b
Variable Tracker
VariableStartAfter Step 2After Step 3Final
inputundefined444
a.call resultundefined666
b.call resultundefinedundefined1818
c.call resultundefinedundefinedundefined18
Key Moments - 3 Insights
Why do we call a.call(z) inside the Proc c instead of just using a(z)?
In Ruby, Procs are objects and need .call to execute. The execution_table row 2 shows a.call(4) producing 6.
What happens if we switch the order and call a.call(b.call(z)) instead?
The order changes the result because b runs first. The execution_table shows the current order: a then b, which matters for output.
Why does c.call(4) return 18?
Because a adds 2 to 4 (6), then b multiplies 6 by 3 (18), as shown in execution_table rows 2 and 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output of a.call(4) at step 2?
A8
B6
C12
D18
💡 Hint
Check execution_table row 2 under Output column
At which step does the Proc b get called during c.call(4)?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at execution_table rows and find where b.call is executed
If we change Proc b to multiply by 4 instead of 3, what would c.call(4) output be?
A24
B18
C20
D16
💡 Hint
Use variable_tracker to find a.call(4) = 6, then multiply by 4
Concept Snapshot
Proc composition in Ruby:
- Define Procs: a = Proc.new { |x| ... }
- Compose: c = Proc.new { |z| b.call(a.call(z)) }
- Call composed Proc: c.call(input)
- Output is b applied to a's output
- Use .call to execute Procs
- Order matters: a then b here
Full Transcript
This example shows how to compose two Procs in Ruby. We define Proc a that adds 2 to input, and Proc b that multiplies input by 3. Then we create Proc c that calls a, then passes its result to b. Calling c.call(4) runs a.call(4) which gives 6, then b.call(6) which gives 18. The final output is 18. We track each step in the execution table and variable changes. Key points include using .call to run Procs and understanding the order of composition affects the result.