Bird
0
0

Given this code, what will be the output?

hard📝 Application Q8 of 15
Ruby - Basics and Runtime
Given this code, what will be the output?
def counter
  count = 0
  lambda do
    count += 1
  end
end

c = counter
puts c.call
puts c.call
AError: undefined method 'call'
B0 0
C1 2
D1 1
Step-by-Step Solution
Solution:
  1. Step 1: Analyze counter method return

    counter returns a lambda that increments count.
  2. Step 2: Check how c is assigned

    c = counter assigns c to the lambda returned by the method (method called).
  3. Step 3: Calling c.call increments count

    Each call to c.call increments count by 1, so outputs 1 then 2.
  4. Final Answer:

    1 2 -> Option C
  5. Quick Check:

    Lambda increments count on each call [OK]
Quick Trick: Use parentheses to call method returning lambda [OK]
Common Mistakes:
  • Assigning method without calling it
  • Expecting lambda without parentheses
  • Confusing method and lambda objects

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes