Consider the following Ruby code using closures and variable binding. What will it print?
def make_procs procs = [] 3.times do |i| procs << Proc.new { i } end procs end procs = make_procs procs.each { |p| puts p.call }
In Ruby, the block variable i is captured by value in each iteration, so each Proc remembers its own i.
Each Proc captures the current value of i during the iteration, so it prints 0, 1, and 2 respectively.
Look at this Ruby code where a closure captures a variable that changes after the closure is created. What is printed?
def counter count = 0 Proc.new { count += 1 } end c = counter puts c.call puts c.call count = 100 puts c.call
The closure captures the local variable count inside the method, not the top-level count.
The Proc closes over the method-local count, keeping it alive and modifying it independently of any outer count.
Examine this Ruby code. It creates an array of Procs inside a loop, but all Procs print the same value. Why?
procs = [] value = 0 3.times do procs << Proc.new { value } value += 1 end procs.each { |p| puts p.call }
Think about what variable the Proc actually remembers and when it is evaluated.
All Procs capture the same value variable. When called later, they all see its final value, which is 3.
Which of these code snippets correctly creates an array of Procs that each remember a different loop variable value?
Try to create a new variable inside the loop to capture the current value.
Option C creates a new variable x inside the loop for each iteration's lexical scope, so each Proc captures a different x with values 0,1,2.
Analyze this Ruby code that uses closures and variable binding. How many elements does the results array contain after execution?
def create_procs procs = [] i = 0 while i < 3 do procs << Proc.new { i } i += 1 end procs end results = create_procs.map(&:call)
Count how many Procs are added to the array inside the loop.
The loop runs 3 times (i=0,1,2), adding one Proc each time, so procs has 3 elements and results will too.