Loops & Iterators

Definition

A loop in Ruby are blocks that are repeated while a certain condition is being met or until a certain condition is reached.

While Loop

A while loop in Ruby is signalled with a keyword while and it repeats a certain block while (i.e. as long as) a certain condition is being met.

count = 10

while count > 0 do
  count -= 1
  print count
end # => 9876543210

The keyword while can also be placed after a block which however makes the block to execute before the condition is checked and therefore the block is always executed at least once.

count = 10

begin
  count -= 1
  print count
end while count > 0 # 9876543210 => nil

A similar construct can be created with an until keyword.

count = 10

until count == 0 do
  count -= 1
  print count
end # 9876543210 => nil

The while and until loops return nil.

For Loop

A for loop goes through a collection of elements and separately executes a block with each of those elements as an argument.

elements = [1,2,3,4,5]

for element in elements
  print element
end

The for loop returns the underlying collection.

Next & Break

When a next keyword is used within a loop it will skip the current iteration and go to the next one.

count = 10

while count > 0 do
  count -= 1
  next if count == 5

  print count
end # 987643210 => nil

When a break keyword is used within a loop it will stop the whole loop.

count = 10

while count > 0 do
  count -= 1
  break if count == 5

  print count
end # 9876 => nil

In addition to next and break there is also a redo keyword in Ruby.

Iterators

Iterators are methods called on Ruby objects that iterate one by one on the objects underlying data. The most notable iterator is each and is discussed under Enumerators section.