Bird
Raised Fist0
Rubyprogramming~10 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What is a lambda in Ruby?
easy
A. A type of loop that repeats code multiple times
B. A special variable that holds numbers only
C. A method that automatically runs when a program starts
D. A small block of code stored in a variable that can be called later

Solution

  1. Step 1: Understand what a lambda represents

    A lambda is a reusable piece of code stored in a variable, like a mini-function.
  2. Step 2: Compare with other options

    Options A, C, and D describe loops, methods, or variables, not lambdas.
  3. Final Answer:

    A small block of code stored in a variable that can be called later -> Option D
  4. Quick Check:

    Lambda = reusable code block [OK]
Hint: Lambdas are like mini-functions stored in variables [OK]
Common Mistakes:
  • Confusing lambdas with loops
  • Thinking lambdas run automatically
  • Believing lambdas hold only numbers
2. Which of the following is the correct way to create a lambda in Ruby?
easy
A. ->(x) { x * 2 }
B. def lambda(x) x * 2 end
C. lambda(x) => x * 2
D. lambda(x) { x * 2 }

Solution

  1. Step 1: Identify valid lambda syntax

    In Ruby, lambdas can be created using the arrow syntax ->(params) { code } or lambda { |params| code }.
  2. Step 2: Check each option

    lambda(x) { x * 2 }: invalid syntax (lambda keyword expects block with |params|, not parenthesized args). def lambda(x) x * 2 end: method definition, not a lambda. lambda(x) => x * 2: invalid syntax. ->(x) { x * 2 }: correct arrow syntax.
  3. Final Answer:

    ->(x) { x * 2 } -> Option A
  4. Quick Check:

    Arrow syntax ->(x) { ... } creates lambda [OK]
Hint: Use ->(params) { code } or lambda { |params| code } [OK]
Common Mistakes:
  • Using def instead of lambda
  • Incorrect arrow syntax
  • Confusing method and lambda syntax
3. What will be the output of this Ruby code?
my_lambda = ->(x) { x + 3 }
puts my_lambda.call(4)
medium
A. 3
B. 4
C. 7
D. Error

Solution

  1. Step 1: Understand the lambda behavior

    The lambda adds 3 to the input number x.
  2. Step 2: Calculate the output

    Calling my_lambda.call(4) computes 4 + 3 = 7.
  3. Final Answer:

    7 -> Option C
  4. Quick Check:

    4 + 3 = 7 [OK]
Hint: Call lambda with .call and input to get output [OK]
Common Mistakes:
  • Forgetting to use .call to invoke lambda
  • Confusing input and output values
  • Expecting syntax error
4. What is wrong with this Ruby code?
my_lambda = lambda { |x, y| x + y }
puts my_lambda.call(5)
medium
A. It will raise an ArgumentError
B. It will print nil
C. It will print 5
D. It will raise a SyntaxError

Solution

  1. Step 1: Check lambda argument requirements

    Lambdas check arguments strictly. This lambda expects 2 arguments (x and y).
  2. Step 2: Analyze the call with one argument

    Calling my_lambda.call(5) provides only 1 argument, causing ArgumentError.
  3. Final Answer:

    It will raise an ArgumentError -> Option A
  4. Quick Check:

    Lambda argument count mismatch = ArgumentError [OK]
Hint: Lambdas need exact argument count or error [OK]
Common Mistakes:
  • Assuming missing arguments default to nil
  • Expecting no error on fewer arguments
  • Confusing lambdas with procs (which are lenient)
5. Given this code, what will be the output?
def test_lambda
  l = -> { return "Inside lambda" }
  result = l.call
  return "Outside lambda"
end
puts test_lambda
hard
A. Inside lambda
B. Outside lambda
C. nil
D. Error

Solution

  1. Step 1: Understand lambda return behavior

    Return inside a lambda exits only the lambda, not the enclosing method.
  2. Step 2: Trace method execution

    The lambda returns "Inside lambda" to variable result, but method continues and returns "Outside lambda".
  3. Final Answer:

    Outside lambda -> Option B
  4. Quick Check:

    Lambda return exits lambda only, method returns after [OK]
Hint: Return inside lambda exits lambda, not method [OK]
Common Mistakes:
  • Thinking return inside lambda exits method
  • Expecting "Inside lambda" as output
  • Confusing lambda with proc return behavior
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard