Challenge - 5 Problems
Ruby Loop Control Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Ruby code using break?
Consider the following Ruby code snippet. What will it print when run?
Ruby
arr = [1, 2, 3, 4, 5] result = [] arr.each do |x| break if x > 3 result << x end puts result.inspect
Attempts:
2 left
💡 Hint
Remember that break exits the loop immediately when the condition is true.
✗ Incorrect
The loop adds elements to result until it encounters a value greater than 3. When x is 4, break stops the loop, so only 1, 2, and 3 are added.
❓ Predict Output
intermediate2:00remaining
What does next do in this Ruby loop?
Look at this Ruby code. What will be printed?
Ruby
result = [] (1..5).each do |i| next if i.even? result << i end puts result.inspect
Attempts:
2 left
💡 Hint
next skips the current iteration and moves to the next one.
✗ Incorrect
The loop skips even numbers using next, so only odd numbers 1, 3, and 5 are added to result.
❓ Predict Output
advanced2:00remaining
What is the output when using redo inside a loop?
Analyze this Ruby code. What will it print?
Ruby
count = 0 (1..3).each do |i| puts i count += 1 redo if count < 3 count = 0 end
Attempts:
2 left
💡 Hint
redo repeats the current iteration without moving to the next element.
✗ Incorrect
For each i, the loop prints i and increments count. redo repeats the iteration until count reaches 3, then resets count and moves on.
🔧 Debug
advanced2:00remaining
Why does this Ruby code cause an infinite loop?
This Ruby code uses redo inside a loop. Why does it never end?
Ruby
i = 0 while i < 3 do puts i redo if i < 3 i += 1 end
Attempts:
2 left
💡 Hint
Think about what redo does to the flow of the loop and when i changes.
✗ Incorrect
redo restarts the current iteration without running the code after it. Since i += 1 is after redo, i never changes, causing an infinite loop.
🧠 Conceptual
expert3:00remaining
How do break, next, and redo differ in Ruby loops?
Which statement correctly describes the behavior of break, next, and redo in Ruby loops?
Attempts:
2 left
💡 Hint
Think about what each keyword does to the flow of the loop.
✗ Incorrect
break stops the loop completely, next skips the rest of the current iteration and moves on, and redo restarts the current iteration without checking the loop condition again.