For in Ruby

Ruby provides several ways to create loops. Here are some basic types of loops in Ruby.

# The most basic type, with a single condition.
i = 1
while i <= 3
  puts i
  i += 1
end

# A classic initial/condition/after loop using times.
3.times do |j|
  puts j
end

# Another way of accomplishing the basic "do this
# N times" iteration is using each with a range.
(0..2).each do |i|
  puts "range #{i}"
end

# Loop without a condition will run repeatedly
# until you break out of the loop or return from
# the enclosing method.
loop do
  puts "loop"
  break
end

# You can also use next to skip to the next iteration of
# the loop.
6.times do |n|
  next if n % 2 == 0
  puts n
end

To run the program, save it as loops.rb and use the ruby command:

$ ruby loops.rb
1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5

Ruby offers various looping constructs, including while, until, for, loop, and iterator methods like times and each. The while loop is similar to the basic condition-only loop in other languages. The times method provides a simple way to repeat an action a specific number of times. The each method, often used with ranges or arrays, is a powerful and idiomatic way to iterate in Ruby.

The loop method creates an infinite loop that continues until explicitly broken. The next keyword in Ruby is equivalent to continue in many other languages, allowing you to skip to the next iteration.

We’ll see some other loop forms later when we look at iterating over collections, working with blocks, and other data structures.