Chris Mendez in For Developers, Ruby

Ruby: Loops

There are a lot of different ways to complete a loop. Here's a list of the most popular ones.

Loop

Loop in increments of 2 until x reaches 20.

x = 0

loop do  
  x += 2
  break if x >= 20
  puts x
end  

Loop through in increments of 2 until you reach 20. If x reaches 6, move on through next if.

x = 0  
loop do  
  x += 2
  break if x >= 20
  next if x == 6
  puts x
end  

While Loop

Block-style while

x = 0

while x < 20  
  x += 2
  puts x
end  

Single line-style while.

x = 0  
puts x += 2 while x < 100  

Until

y = 3245  
puts y /= 2 until y <= 1  

Iterators

Traversing through a fixed set of data

Times do

Iterate 5 times.

5.times do  
  puts "Hello"
end  

Up to

Single line style.

1.upto(5) { puts "hello" };  

Block style.

1.upto(5) do |i|  
  puts "hello " + i.to_s
end  

This example is similar to the one above with with an explicit each.

1.upto(3).each do |i|  
  puts "hello " + i.to_s
end  

Down to

Single line.

5.downto(1) { puts "hello" };  

Each

Use each on a Range.

(1..5).each { puts "hello" };

Present each as a block.

fruits = [ 'banana', 'apple', 'pear' ]  
fruits.each do |fruit|  
  puts fruit.capitalize
end  

For In

fruits = [ 'banana', 'apple', 'pear' ]  
for fruit in fruits  
  puts fruit.capitalize
end  

This uses for and step to increment by 2 within a range of 0 and 10.

for i in (0..10).step(2) do  
    puts i
end  

Step Iterator

This is really handy if you're doing something like a clock or stopwatch.

(time1..time2).step(15.minutes) do |time|
end  

Use Range and go from 0 to 10 in increments of 1.

(0..10).step(1) do |i|
  puts "Hello #{i}"
end  

Start at one and go to 5 in increments of one.

1.step(5,1) do |i|  
  puts "Hello #{n}"
end  

Resources