Bird
0
0

How can you modify this Ruby code to create closures that each remember a different value of i even if i changes later?

hard📝 Application Q15 of 15
Ruby - Blocks, Procs, and Lambdas
How can you modify this Ruby code to create closures that each remember a different value of i even if i changes later?
closures = []
3.times do |i|
  closures << lambda { i }
end
closures.each { |c| puts c.call }
ACall closures inside the times block
BChange lambda to proc
CUse global variable $i instead of i
DUse a local variable inside the block to capture i: <code>val = i; closures << lambda { val }</code>
Step-by-Step Solution
Solution:
  1. Step 1: Understand variable capture in closures

    Closures capture variables by reference, so if i changes later, all lambdas see the last value.
  2. Step 2: Use a local variable to capture current value

    Assign val = i inside the block, then create lambda using val. This captures the value at that iteration.
  3. Final Answer:

    Use a local variable inside the block to capture i: val = i; closures << lambda { val } -> Option D
  4. Quick Check:

    Capture current value with local variable [OK]
Quick Trick: Assign loop variable to local var inside block for closure [OK]
Common Mistakes:
  • Thinking proc changes variable capture behavior
  • Using global variables which share state
  • Calling closures too early inside loop

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes