Loops

For ... in

for element in myArray
statements
end
  • Internally resolves to the following:
myArray.each do |element|
statements
end

While loop

while expr
statements
end
single-statement while expr

Until loop

until expr
statements
end
single-statement until expr

Loop

loop {
statements
}

Each loop

<array>.each block
<range>.each block
  • Iterates through each element of the array or range
[1, 2, 3].each { |x| puts x }

('a'..'e').each do |x|
puts x
end

Times loop

<number>.times block
  • Iterates from 0 to n - 1
5.times { |x| puts x }

5.times do |x|
puts x
end

Upto loop

<number>.upto(<number>) block
  • Iterates from m to n inclusively
3.upto(6) { |x| puts x }

3.upto(6) do |x|
puts x
end

Jump statements

  • next    # Continue on to the next iteration of the loop
  • break  # Break from the loop
  • redo   # Repeat the current iteration of the loop
  • retry   # Restart the loop from the beginning