0
0
Rubyprogramming~10 mins

For loop (rarely used in Ruby) - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - For loop (rarely used in Ruby)
Initialize loop variable
Check condition: variable in range?
NoEXIT
Yes
Execute loop body
Update loop variable to next value
Back to Check
The for loop starts by setting a variable, checks if it is within a range, runs the loop body if yes, then moves to the next value until the condition fails.
Execution Sample
Ruby
for i in 1..3
  puts i
end
This code prints numbers 1 to 3 using a for loop.
Execution Table
Iterationi valueCondition (i in 1..3)ActionOutput
11truePrint i1
22truePrint i2
33truePrint i3
44falseExit loop
💡 Next value 4 is outside 1..3, so condition is false and loop stops
Variable Tracker
VariableStartAfter 1After 2After 3Final
iundefined1234
Key Moments - 2 Insights
Why does the loop stop after printing 3?
Because the condition checks if i is in 1..3. After i=3, next would be 4 (see execution_table row 4), it is outside the range, so the loop ends.
Is the loop variable i accessible after the loop ends?
Yes, in Ruby the loop variable i keeps its last value after the loop (which is 4 here, see variable_tracker final).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of i during iteration 2?
A1
B2
C3
D4
💡 Hint
Check the 'i value' column in execution_table row for iteration 2.
At which iteration does the loop condition become false?
AIteration 4
BIteration 1
CIteration 3
DIteration 2
💡 Hint
Look at the 'Condition' column in execution_table where it changes to false.
If the range changed to 1..2, how many times would the loop run?
A3 times
B1 time
C2 times
D4 times
💡 Hint
Refer to how the range controls iterations in execution_table and variable_tracker.
Concept Snapshot
for loop syntax:
for variable in range
  # code
end

Runs code for each value in range.
Stops when values end.
Loop variable keeps last value after loop.
Full Transcript
This visual trace shows how a for loop works in Ruby. The loop variable i starts at 1 and goes up to 3. Each iteration prints i. After printing 3, next would be 4 but condition fails and the loop stops. The variable i keeps its last value after the loop ends. This example helps beginners see each step clearly.