Loops

Loop n times

Take a look at the following syntax examples of running a block of codes n times.

Using times method on the Int type:

5.times do
  p "hi!"
end

Using a block in curly brackets:

t.times {
  p "hi!"
}

Iterating over Array and Range types

Example 1:

friends = ["John", "Martha", "Paige", "Cooper", "Herbert"]

friends.each do |friend|
  puts friend # => John, Martha, Paige, Cooper, Herbert
end

Example 2:

friends = ["John", "Martha", "Paige", "Cooper", "Herbert"]
(1...3).each do |friend|
  puts friend # => Martha, Paige
end

Using loop do

You can express a custom logic with loop do:

x = 1
loop do
  puts "x = #{x}"
  x += 1
  break if x == 3
end

Using a classic while loop

x = 1
while (x += 1) < 10
  p j # => 2, 3, 4, 5, 6, 7, 8, 9
end

Within loop constructs, you can use next and break statements:

x = 1
while (x += 1) < 10
  if x == 3
    next # jump to next iteration
  elsif j > 6
    break # break loop here
  end
  puts x # => 2, 4, 5, 6
end

Use unless for the inverse

x = 5
until (z -= 1) == 0
  p z # => 4, 3, 2, 1
end