0
0
Rubyprogramming~20 mins

Break, next, and redo behavior in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Loop Control Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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
A[1, 2, 3]
B[1, 2]
C[1, 2, 3, 4]
D[1, 2, 3, 4, 5]
Attempts:
2 left
💡 Hint
Remember that break exits the loop immediately when the condition is true.
Predict Output
intermediate
2: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
A[]
B[2, 4]
C[1, 2, 3, 4, 5]
D[1, 3, 5]
Attempts:
2 left
💡 Hint
next skips the current iteration and moves to the next one.
Predict Output
advanced
2: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
A
1
1
1
1
1
... (infinite loop)
B
1
2
3
C
1
1
1
2
2
2
3
3
3
D
1
2
2
3
3
3
Attempts:
2 left
💡 Hint
redo repeats the current iteration without moving to the next element.
🔧 Debug
advanced
2: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
ABecause i is never incremented before redo repeats the iteration, so i stays 0 forever.
BBecause redo skips the i += 1 line, so i increments too fast.
CBecause the condition i < 3 is always false.
DBecause puts i causes an error stopping the loop.
Attempts:
2 left
💡 Hint
Think about what redo does to the flow of the loop and when i changes.
🧠 Conceptual
expert
3: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?
Abreak exits the entire loop immediately; next skips to the next iteration; redo repeats the current iteration without re-evaluating the loop condition.
Bbreak skips the current iteration; next exits the loop; redo moves to the next iteration.
Cbreak repeats the current iteration; next exits the loop; redo skips the current iteration.
Dbreak and next both exit the loop; redo skips the rest of the loop body.
Attempts:
2 left
💡 Hint
Think about what each keyword does to the flow of the loop.