Bird
0
0

What will be the output of this Ruby code?

medium📝 Predict Output Q4 of 15
Ruby - Loops and Iteration
What will be the output of this Ruby code?
count = 1
loop do
  puts count
  break if count >= 3
  count += 1
end
AInfinite loop printing 1
B1 2
C1 2 3 4
D1 2 3
Step-by-Step Solution
Solution:
  1. Step 1: Trace the loop iterations

    First iteration: count=1, prints 1, count < 3 so continue.
    Second iteration: count=2, prints 2, count < 3 so continue.
    Third iteration: count=3, prints 3, break if count >= 3 triggers break after printing.
  2. Step 2: Check output sequence

    Loop prints 1, then 2, then 3 and breaks immediately after printing 3.
  3. Final Answer:

    1 2 3 -> Option D
  4. Quick Check:

    Loop prints until break condition met = 1 2 3 [OK]
Quick Trick: break stops loop after printing current count [OK]
Common Mistakes:
MISTAKES
  • Assuming break stops before printing current value
  • Thinking loop runs infinitely
  • Misreading the break condition

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes