For loops

1134 views

What's the return value of the following Ruby code?

i = 42

for i in (1...10)
  puts i
end

i # => ???

The correct answer is

42

10

nil

9

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

Explanation

In the provided code snippet, there's a common misconception about how the variable i is being modified within the loop. Let me break it down for you:

i = 42

for i in (1...10)
  puts i
end

i # => 9

At first glance, it might seem like the variable i should retain its initial value of 42 since it's defined outside the loop.

However, in Ruby, the for...in loop doesn't create a new scope for the loop variable i.

Instead, it reuses the existing variable i defined outside the loop, effectively modifying its value.

Here's a step-by-step explanation of what happens:

  1. i is initialized with the value 42.
  2. The for...in loop iterates over the range (1...10), which includes integers from 1 to 9 (inclusive).
  3. During each iteration of the loop, the loop variable i takes on the value of the current element in the range (1...10). So, i is successively assigned the values 1, 2, 3, ..., 9.
  4. After the loop completes, the value of i is 9, which is the last value assigned to it within the loop.

Therefore, when you print the value of i after the loop (i # => 9), it reflects the final value assigned to i within the loop.

Here's a more explicit example to demonstrate the behavior:

i = 42

for j in (1...10)
  puts "j = #{j}, i = #{i}"
  i = j * 2
end

puts "Outside loop: i = #{i}"

This will output:

j = 1, i = 42
j = 2, i = 2
j = 3, i = 4
j = 4, i = 6
j = 5, i = 8
j = 6, i = 10
j = 7, i = 12
j = 8, i = 14
j = 9, i = 16
Outside loop: i = 16

As you can see, the value of i is modified within the loop and retains its final value (16) after the loop completes.

Voilà!

Unlock Your Ruby Potential

Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!

RubyCademy ©