Bird
0
0

You want to create an array of lambdas where each lambda returns the square of its index (0 to 4). Which code correctly achieves this using closures?

hard📝 Application Q8 of 15
Ruby - Blocks, Procs, and Lambdas
You want to create an array of lambdas where each lambda returns the square of its index (0 to 4). Which code correctly achieves this using closures?
Aarr = [] 5.times do |i| arr << lambda { i * i } end
Barr = [] 5.times do |i| val = i arr << lambda { val * val } end
Carr = [] 5.times do |i| arr << lambda { i } end
Darr = [] 5.times do |i| arr << lambda { i ** 2 } end
Step-by-Step Solution
Solution:
  1. Step 1: Understand variable capture in closures

    Using block variable i directly in lambda captures the variable, which may change.
  2. Step 2: Use a local variable to capture current value

    Assign i to val inside the block, then use val in lambda to capture the value at each iteration.
  3. Final Answer:

    arr = [] 5.times do |i| val = i arr << lambda { val * val } end -> Option B
  4. Quick Check:

    Use local variable to fix closure capture [OK]
Quick Trick: Assign block variable to local var before lambda to capture value [OK]
Common Mistakes:
  • Using block variable directly causing all lambdas to return last value
  • Confusing * and ** operators
  • Ignoring variable binding inside closures

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes