0
0
Rubyprogramming~10 mins

While loop in Ruby - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - While loop
Initialize variable
Check condition
|Yes
Execute loop body
Update variable
Back to Check
Exit loop
Back to Check
The while loop starts by checking a condition. If true, it runs the loop body, updates variables, then checks again. It stops when the condition is false.
Execution Sample
Ruby
i = 0
while i < 3
  puts i
  i += 1
end
This code prints numbers 0, 1, and 2 by looping while i is less than 3.
Execution Table
StepiCondition (i < 3)ActionOutput
10truePrint 0, i = i + 10
21truePrint 1, i = i + 11
32truePrint 2, i = i + 12
43falseExit loop
💡 i reaches 3, condition 3 < 3 is false, loop stops
Variable Tracker
VariableStartAfter 1After 2After 3Final
i01233
Key Moments - 2 Insights
Why does the loop stop when i equals 3?
Because the condition i < 3 becomes false at step 4, so the loop does not run again (see execution_table row 4).
What happens if we forget to update i inside the loop?
The condition stays true forever, causing an infinite loop. The variable i must change to eventually make the condition false.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of i at step 2?
A2
B0
C1
D3
💡 Hint
Check the 'i' column in execution_table row 2.
At which step does the condition become false and the loop stops?
AStep 4
BStep 3
CStep 1
DStep 2
💡 Hint
Look at the 'Condition' column in execution_table where it changes to false.
If we change the condition to i < 5, how many times will the loop run?
A3 times
B5 times
C4 times
D6 times
💡 Hint
Refer to variable_tracker and how i increments until condition is false.
Concept Snapshot
while condition do
  # code to repeat
  update variables
end

- Checks condition before each loop
- Runs body only if condition true
- Stops when condition false
- Update variables inside to avoid infinite loop
Full Transcript
This visual shows how a while loop works in Ruby. We start with i = 0. The loop checks if i is less than 3. If yes, it prints i and adds 1 to i. This repeats until i reaches 3, when the condition becomes false and the loop stops. The variable i changes from 0 to 3 step by step. If we forget to update i, the loop never ends. Changing the condition changes how many times the loop runs.