0
0
Rubyprogramming~10 mins

Proc creation and call in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Proc creation and call
Create Proc object
Store Proc in variable
Call Proc using .call
Execute Proc code block
Return result from Proc
Use or print result
This flow shows how a Proc is created, stored, called, and how its result is used.
Execution Sample
Ruby
my_proc = Proc.new { |x| x * 2 }
result = my_proc.call(5)
puts result
Creates a Proc that doubles a number, calls it with 5, and prints the result.
Execution Table
StepActionEvaluationResult
1Create Proc with block { |x| x * 2 }Proc object createdmy_proc holds Proc
2Call my_proc.call(5)Executes block with x=5Returns 10
3Assign result = 10Store return valueresult = 10
4puts resultPrints value to outputOutput: 10
💡 Program ends after printing 10
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
my_procnilProc objectProc objectProc objectProc object
resultnilnil101010
Key Moments - 2 Insights
Why do we use .call to run the Proc instead of just writing its name?
The Proc object is like a box holding code. To run the code inside, we must use .call as shown in step 2 of the execution_table.
What does the block parameter |x| mean inside the Proc?
It is a placeholder for the input value given when calling the Proc, like 5 in step 2. The Proc uses x to do calculations.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of result after step 3?
A5
BProc object
C10
Dnil
💡 Hint
Check the 'result' variable in variable_tracker after step 3.
At which step is the Proc object created and stored in my_proc?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the first row in execution_table where the Proc is created.
If we change the call to my_proc.call(3), what will be the output at step 4?
A10
B6
C3
DError
💡 Hint
The Proc doubles the input, so check the calculation in step 2.
Concept Snapshot
Proc creation: my_proc = Proc.new { |x| code }
Call Proc: my_proc.call(args)
Proc holds code block to run later
.call runs the code with given input
Returns result from block
Full Transcript
This example shows how to create a Proc in Ruby using Proc.new with a block that takes one input x and returns x times 2. The Proc is stored in the variable my_proc. When we call my_proc.call(5), it runs the block with x=5 and returns 10. We store this in result and print it with puts, which outputs 10. The key steps are creating the Proc, calling it with an argument, and using the returned value.