A loop in Ruby are blocks that are repeated while a certain condition is being met or until a certain condition is reached.
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
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
count = 10 until count == 0 do count -= 1 print count end # 9876543210 => nil
until loops return
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
for loop returns the underlying collection.
Next & Break
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
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
break there is also a
redo keyword in Ruby.
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.