0
0
Rubyprogramming~10 mins

Lambda creation and behavior in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Lambda creation and behavior
Define lambda with -> syntax
Store lambda in variable
Call lambda with .call
Execute lambda body
Return result from lambda
Use result or print output
This flow shows how a lambda is created, stored, called, and returns a result in Ruby.
Execution Sample
Ruby
my_lambda = ->(x) { x * 2 }
result = my_lambda.call(5)
puts result
This code creates a lambda that doubles a number, calls it with 5, and prints the result.
Execution Table
StepActionEvaluationResult
1Define lambda with ->(x) { x * 2 }Creates a lambda functionmy_lambda stores lambda
2Call lambda with my_lambda.call(5)Passes 5 as argument xExecutes body: 5 * 2
3Calculate 5 * 2Multiply 5 by 210
4Return result from lambdaReturns 10result = 10
5Print resultOutputs to console10
💡 Lambda call completes and program ends after printing result
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 4Final
my_lambdanillambda functionlambda functionlambda functionlambda function
resultnilnil101010
Key Moments - 2 Insights
Why does the example use .call to run the lambda?
In Ruby, lambdas are Proc objects stored in variables. The example uses .call to invoke it (see execution_table step 2). Parentheses also work: you could use my_lambda(5) instead.
What happens if we pass a different number of arguments to the lambda?
Lambdas check the number of arguments strictly. Passing wrong number causes an error (not shown here but important to know). This is different from procs.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'result' after step 4?
Anil
B5
C10
Dlambda function
💡 Hint
Check the 'result' variable in variable_tracker after step 4
At which step is the lambda actually executed?
AStep 2
BStep 1
CStep 3
DStep 5
💡 Hint
Look at execution_table where .call is used to run the lambda
If we change the lambda to ->(x) { x + 3 }, what will be printed?
A15
B8
C10
D5
💡 Hint
Think about the lambda body and input 5, see execution_table step 3 for calculation
Concept Snapshot
Lambda creation in Ruby:
- Use ->(args) { body } to define
- Store in variable
- Call with .call(args) or (args)
- Lambda checks argument count strictly
- Returns last expression value
- Useful for small reusable functions
Full Transcript
This example shows how to create and use a lambda in Ruby. First, we define a lambda that doubles its input using the ->(x) { x * 2 } syntax and store it in the variable my_lambda. Next, we call this lambda with the argument 5 using my_lambda.call(5). The lambda executes its body, multiplying 5 by 2, resulting in 10. This value is returned and stored in the variable result. Finally, we print the result, which outputs 10. Remember, lambdas can be called with .call (as shown) or parentheses like my_lambda(5), and check argument counts strictly.