≡ Menu

20 Practical Ruby Loop Command Examples – For, Each, While, Until

Looping through stuff is an important aspect of any programming language.

In several of our previous tutorials, we explained in detail various loops including python for loop, for loops in c programming, loops in awk scripting, loops in bash shell scripting, etc.

The focus of this article is on how to loop through stuff in Ruby.

In Ruby programming language, on a very high-level, the following are 8 different types of commands (functions) that you can use to loop through stuffs.

  1. Loop
  2. Until
  3. While
  4. Do – While
  5. For
  6. Each
  7. Upto
  8. Times

In this tutorial, we’ll discuss the following 20 examples that will cover all of the Ruby loop related commands.

  1. Quick Summary – For the Impatient
  2. Loop Command – Just Keeps Looping
  3. Loop Command – Break out of It
  4. Loop Command – Just Skip one Particular Loop using Next
  5. Until Command – Keep looping until it is true
  6. While Command – While it is true, keep looping
  7. Do-While Loop – While at the end of the block
  8. For Command – Loop through a Number Range
  9. For using Array – Loop through an Array of Elements
  10. For using Array Length
  11. For using Array Size
  12. For inside a For – Nested For Loops
  13. Each Command – Popular Loop Method in Ruby
  14. Each Command – Loop through Multiple Strings in an Array
  15. Each_Index Command – Loop through Only Array Indexes
  16. Each_with_Index Command – Loop through an Array using Index and Value
  17. Each inside a Each – Nested Each Command
  18. Each Command – Loop through Static Number Ranges
  19. Times Command – Loop through X number of Times
  20. Upto Command – Loop through Upto X number Starting from Y

1. Quick Summary – For the Impatient

For the impatient, quick snippets of major loop commands are shown below. For more details on these commands, read through the full tutorial.

Loop command:

loop do
 puts "do something"
end

Until command:

until count > 5
  puts "do something"
end

While command:

while count <= 5
  puts "do something"
end

For command – loop 5 times

for i in 1..5 do
  puts "#{i}"
end

For command – loop through an array:

for i in myarray do
  puts "#{i}"
end

Each command – loop 5 times

(1..5).each do |i|
  puts "#{i}"
end

Each command – loop through an array

myarray.each do |element|
  puts "#{element}"
end

Each command – loop through an array with both index and elements

myarray.each_with_index do |element,i|
  puts "#{i}. #{element}"
end

Times command – loop 5 times

5.times do |i|
  puts "#{i}"
end

Upto command – loop from 2 through 5

2.upto(5) do |i|
  puts "#{i}"
end

2. Loop Command – Just Keeps Looping

The first is the loop command itself. All it does is that it keeps going on an infinite loop.

As you see below, the following basic loop command example, will repeatedly keep printing the stuff between the “do” and “end” block until you press Ctrl-C

# cat loop1.rb
loop do
  puts "The Geek Stuf"
  puts "Press Ctrl-C to Exit!"
end

Execute the above program to test it. Make sure you press Ctrl-C to exit out of the loop

# ruby loop1.rb
The Geek Stuf
^CPress Ctrl-C to Exit!
loop1.rb:2: Interrupt
    from loop1.rb:1:in `loop'
    from loop1.rb:1

Also, keep in mind that for pretty much any loop commands in Ruby, instead of “do” and “end” you can also specify the body of the loop within curly brackets { } as shown below.

The following example is exactly same as above, but using braces .

# cat loop2.rb
loop {
  puts "The Geek Stuf"
  puts "Press Ctrl-C to Exit!"
}

Warning: Don’t give { on a separate line! If you do, you’ll get an error message. The following is not correct as the { is on the next line to loop. It should be on the same line as loop command.

# cat loop2.rb
loop
{
  puts "The Geek Stuf"
  puts "Press Ctrl-C to Exit!"
}

The above example will throw the following error message.

# ruby loop2.rb
loop2.rb:3: syntax error, unexpected tSTRING_BEG, expecting kDO or '{' or '('
  puts "The Geek Stuf"
        ^
loop2.rb:5: syntax error, unexpected '}', expecting $end

3. Loop Command – Break out of It

The previous loop command example is pretty much useless as it just keeps looping through.

So, to break out of a loop command, use the break command as shown below.

When you do a “break”, it will just stop the execution of the loop and come out.

# cat loop3.rb
loop do
  puts "The Geek Stuff"
  break
end

The above example will loop through just one time.

# ruby loop3.rb
The Geek Stuff

Looping through just one time, is pretty much useless also. So, in the following loop command example, it will loop through total of 5 times before breaking out of the loop.

As you can imagine, to keep track of the number of times to loop, we are using a variable called count and increment it by 1 every time. When the value of the count is equal to 6, we’ll break out of the loop.

# cat loop4.rb
count = 1
loop do
  puts "#{count}" " The Geek Stuff"
  count = count + 1
  if count == 6
    break
  end
end

The following is the output of the above example, which loops through exactly 5 times.

# ruby loop4.rb
1 The Geek Stuff
2 The Geek Stuff
3 The Geek Stuff
4 The Geek Stuff
5 The Geek Stuff

4. Loop Command – Just Skip one Particular Loop using Next

Just like break, inside a loop command, you can also use next.

Next will just skip the rest of the commands in the loop-block for the current execution, but will continue the loop from the top again.

So, in the following example, using if command, we are checking if the value of count is 3. When it is 3, we are executing “next” command, which will skip the remainder of the loop-block and continue the loop from the top again.

This means that the following example will skip only the 3rd execution of the loop.

# cat loop5.rb
count = 1
loop do
  if count == 3
    count = count + 1
    next
  end
  puts "#{count}" " The Geek Stuff"
  count = count + 1
  if count == 6
    break
  end
end

The following output indicates that the above example has skipped the 3rd execution of the loop.

# ruby loop5.rb
1 The Geek Stuff
2 The Geek Stuff
4 The Geek Stuff
5 The Geek Stuff

5. Until Command – Keep looping until it is true

Until is another type of ruby command to loop through stuff.

In until command, the body will get executed until the condition is true. i.e Keep looping as long the condition is false. When the condition becomes true, it will stop the loop.

In the following example, as long as the value of the variable count is not greater than 5, it will keep looping. When the condition becomes true (i.e when count is greater than 5), it will stop looping.

# cat until1.rb
count = 1
until count > 5
  puts "#{count}" " The Geek Stuff"
  count = count + 1
end

As you see from the output below, the above example has executed the loop 5 times using until command.

# ruby until1.rb
1 The Geek Stuff
2 The Geek Stuff
3 The Geek Stuff
4 The Geek Stuff
5 The Geek Stuff

6. While Command – While it is true, keep looping

The second type of command to loop through stuff is while command.

In while command, the body will get executed as long the condition specified in the while command is true.

So, the idea here is that while the condition is true, it will keep looping forever. So, it is your responsibility to make sure the condition becomes false at some point in time.

In the following example, the while will keep looping the body until the count is less than or equal to 5. We are increasing the count inside the loop-body.

So, the following example will loop through 5 times.

# cat while1.rb
count = 1
while count <= 5
  puts "#{count}" " The Geek Stuff"
  count = count + 1
end

As you see from the output below, the above example has executed the loop 5 times using while command.

# ruby while1.rb
1 The Geek Stuff
2 The Geek Stuff
3 The Geek Stuff
4 The Geek Stuff
5 The Geek Stuff

7. Do-While Loop – While at the end of the block

In the previous example, we had the while command at the beginning of the loop.

Typically in most programming languages, when you put the while command at the end of the loop, it is called do-while loop.

Ruby also supports the format of do-while as shown in the following example.

One thing to keep in mind here is that, a do-while loop will always execute the body of the loop at-least once.

This is because we are not checking for any condition at the beginning of the loop. So, the first time the loop is always executed.

At the end of the 1st loop, the condition is checked. As long as the condition is true, it will keep looping.

So, the following example will execute the loop 1st time, and then as long as the condition is true, it will keep looping.

# cat do-while1.rb
count = 1
begin
  puts "#{count}" " The Geek Stuff"
  count = count + 1
end while count <= 5

As you see from the output below, the above example has executed the loop 5 times using do-while command.

# ruby do-while1.rb
1 The Geek Stuff
2 The Geek Stuff
3 The Geek Stuff
4 The Geek Stuff
5 The Geek Stuff

8. For Command – Loop through a Number Range

Almost all programming languages have a for command to loop through stuff. Ruby is no exception.

The following example shows how to loop through a range of numeric values using a simple for loop.

The range is specified in the format of start-value and end-value separated by two periods (without any space in between them)

In the following example, the start-value of the range is 1. The end-value of the range is 5. count is the name of the variable that hold the current value of the loop.

# cat for1.rb
for count in 1..5 do
  puts "#{count}" " The Geek Stuff"
end

The following output indicates that the above example executed the loop 5 times using for command

# ruby for1.rb
1 The Geek Stuff
2 The Geek Stuff
3 The Geek Stuff
4 The Geek Stuff
5 The Geek Stuff

9. For using Array – Loop through an Array of Elements

Apart from giving a number range in the for command, you can also specify an array of elements to loop through.

In the following example, we have an array called “myarray”. In the for command, we’ve just specified this array name to loop through.

This will just loop through all the elements in the array one by one using the for command.

# cat for2.rb
myarray = [ 101, 201, 301, 401, 501 ]
for i in myarray do
  puts "#{i}"
end

As you see from the following output, it looped through all the elements in the array and printed them accordingly.

# ruby for2.rb
101
201
301
401
501

You can also loop through an array with string values as shown below.

# cat for2.1.rb
myarray = [ "The", "Geek", "Stuff" ]
for i in myarray do
  puts "#{i}"
end

As you see from the following output, the above example just looped through myarray which contains three string elements and printed them out.

# ruby for2.1.rb
The
Geek
Stuff

10. For using Array Length

In a for loop command, you can also specify the array-length in the range as the end-value to loop through an array as shown below.

# cat for3.rb
myarray = [ "The", "Geek", "Stuff" ]
maxsize = myarray.length
for i in 1..maxsize
  puts "#{i}" " The Geek Stuff"
end

In the above example, myarray contains total of three elements. So, marray.length will return 3. We are using this value in the for command range as 1..maxsize

So, we are not really looping through the array. We are kind of looping through the array indexes indirectly. There is a better method to loop through an array using indexes, which is explained in one of the following examples.

As you see from the following output, the loop is executed, exactly 3 times, which is the length of the array.

# ruby for3.rb
1 The Geek Stuff
2 The Geek Stuff
3 The Geek Stuff

11. For using Array Size

The following example is very similar to the previous example. But, we are using array size instead of length.

# cat for4.rb
myarray = [ "The", "Geek", "Stuff" ]
for i in 0...myarray.size
  puts "#{i}" " The Geek Stuff"
end

Keep in mind that:
Array length will return how many elements are in the array. We got 3 in previous example. So, if you want to loop through from 1, 2, 3 — use array length.
Array size will return total number of elements in the array minus 1. So, we got 2 in this example. So, if you want to loop through from 0, 1, 2 — use array size.

As you see from the following output, the array size returned 2. So, we are looping through from 0 through 2 in our for loop range.

# ruby for4.rb
0 The Geek Stuff
1 The Geek Stuff
2 The Geek Stuff

12. For inside a For – Nested For Loops

You can also have for loop inside a for loop. This is called nested for loops as shown in the following example.

The outer for loop will loop through the “names” array. The inner for loop will loop through the “things” array.

So, for each person in the names array, it will loop through every item in the things array.

# cat for5.rb
names = [ "John", "Jason", "Lisa" ]
things = [ "Chocolate", "Sugar" ]
counter = 1
for name in names
  puts "#{counter}. #{name} likes: "
  counter = counter + 1
  for item in things
    puts "  #{item}"
  end
end

As you see from the following output, for each person, it has looped through all the things using a nested for loop format.

# ruby for5.rb
1. John likes:
  Chocolate
  Sugar
2. Jason likes:
  Chocolate
  Sugar
3. Lisa likes:
  Chocolate
  Sugar

13. Each Command – Popular Loop Method in Ruby

In Ruby, the recommended method to loop through stuff is using each command as shown below.

The syntax of each command is bit different than the traditional for loop, while loop, etc.

The following example explains how to loop through an array of numbers using each command in ruby.

# cat iterator1.rb
counter = [ 1, 2, 3, 4, 5 ]
counter.each do |i|
  puts "#{i} The Geek Stuff"
end

In the above:

  • counter is the name of the array that contains array of numbers.
  • counter.each – Here we are adding .each to the array variable name. This will loop through the counter array.
  • do … end – This is the loop body (just like other loop command examples)
  • |i| – This is specific to each command. This indicates that the variable i will hold the current value of the array during the looping. You can use this variable to manipulate the individual array element in side the array.

As you see from the following output, we’ve looped through the array variable using the each command and printed the output.

# ruby iterator1.rb
1 The Geek Stuff
2 The Geek Stuff
3 The Geek Stuff
4 The Geek Stuff
5 The Geek Stuff

14. Each Command – Loop through Multiple Strings in an Array

This is similar to the previous each example, but instead of looping through an array of numbers, here we are looping through an array of strings.

# cat iterator2.rb
title = [ "The", "Geek", "Stuff" ]
counter = 1
title.each do |i|
  puts "#{counter}. #{i}"
  counter = counter + 1
end

As you see from the following output, the each command has looped through out title array and printed all the individual elements one by one.

# ruby iterator2.rb
1. The
2. Geek
3. Stuff

15. Each_Index Command – Loop through Only Array Indexes

If you just want to loop through the indexes of the array and not the array elements themselves, then use the each_index command as shown below.

# cat iterator4.rb
title = [ "The", "Geek", "Stuff" ]
title.each_index do |i|
  puts "#{i}"
end

In the above:

  • title is the array that contains three string elements.
  • title.each_index – This indicates that we like to loop through the indexes of our title array (not the array elements, just the index of the elements)
  • do … end – This is the loop body (just like other loop command examples)
  • |i| – This indicates that the variable i will hold the current value of whatever we are looping through. Since we are looping through the indexes, this will hold the current value of the index that we are looping through.

As you see from the following output, this has printed the indexes of the array elements. Since we have three elements in the array, this example has printed 0, 1 and 2.

# ruby iterator4.rb
0
1
2

Please keep in mind that array index always starts from 0 (not from 1)

16. Each_with_Index Command – Loop through an Array using Index and Value

While it is great that each command loops through elements, and each_index loops through indexes.

What if you want to loop through both indexes and elements.

That is exactly why we have each_with_index command as shown in the following example.

In this example, the each_with_index will loop through each individual item, and store both the element value and index value during the loop-body execution in two different variables.

# cat iterator3.rb
title = [ "The", "Geek", "Stuff" ]
title.each_with_index do |element,i|
  puts "#{i}. #{element}"
end

In the above:

  • title is the array that contains three string elements.
  • title.each_with_index – This indicates that we like to loop through both the array values and indexes
  • do … end – This is the loop body (just like other loop command examples)
  • |element,i| – Here we are specifying two variables. The 1st variable (element) will hold the value of the individual array element. The 2nd variable i will hold the value of the indexes of that particular element.
  • puts “#{i}. #{element}” – In the loop body, we are using both individual element and it’s corresponding index value.

As you see from the following output, this example prints both the index and the individual array element value.

# ruby iterator3.rb
0. The
1. Geek
2. Stuff

17. Each inside a Each – Nested Each Command

You can also have each inside an each. This is called Nested each, which is similar to the nested for loop example that we saw earlier.

The outer for loop will loop through the “names” array. The inner for loop will loop through the “things” array.

So, for each person in the names array, it will loop through every item in the things array.

# cat iterator5.rb
names = [ "John", "Jason", "Lisa" ]
things = [ "Chocolate", "Sugar" ]
counter = 1
names.each do |name|
  puts "#{counter}. #{name} likes: "
  counter = counter + 1
  things.each do |item|
    puts "  #{item}"
  end
end

As you see from the following output, for each person, it has looped through all the things using a nested each loop format.

# ruby iterator5.rb
1. John likes:
  Chocolate
  Sugar
2. Jason likes:
  Chocolate
  Sugar
3. Lisa likes:
  Chocolate
  Sugar

18. Each Command – Loop through Static Number Ranges

Instead of looping through an array, you can also loop through static numbers from a range as shown in the following example.

# cat iterator6.rb
(1..5).each do |counter|
  puts "#{counter} The Geek Stuff"
end

In the above:

  • (1..5).each – This indicates that we’ll be looping through the given range using each command. The given range is 1 through 5
  • do … end – This is the loop body (just like other loop command examples)
  • |counter| – This indicates that the variable counter will hold the current value of whatever we are looping through.

As you see from the following output, ther above command has looped through the given static range using each command.

# ruby iterator6.rb
1 The Geek Stuff
2 The Geek Stuff
3 The Geek Stuff
4 The Geek Stuff
5 The Geek Stuff

19. Times Command – Loop through X number of Times

Times is a very helpful loop command, which will help you to quickly loop through x number of times.

The following example will loop through the loop-body 5 times.

# cat times1.rb
5.times do |i|
  puts "#{i} The Geek Stuff"
end

In the above:

  • 5.times – This indicates that number of time that we like to loop through. Here we’ll be looping through 5 times
  • do … end – This is the loop body (just like other loop command examples)
  • |i| – This indicates that the variable i will hold the current value of the loop counter i.e 1st loop, or 2nd loop, or 3rd loop, etc.

One important thing to keep in mind is that, the times command will always start from 0.

So, when we say 5.times, it means: 0, 1, 2, 3 and 4

As you see from the following output, the above example looped through 5 times, but starting from 0 through 4.

# ruby times1.rb
0 The Geek Stuff
1 The Geek Stuff
2 The Geek Stuff
3 The Geek Stuff
4 The Geek Stuff

20. Upto Command – Loop through Upto X number Starting from Y

Another useful command is upto.

Unlike times command, you can specify the starting number for the loop.

The following example is similar to the previous example, but it starts from 1 (instead of 0) and loops through 5 times.

# cat upto1.rb
1.upto(5) do |i|
  puts "#{i} The Geek Stuff"
end

As you see from the following output, the above example looped through 5 times, but starting from 1 through 5.

# ruby upto1.rb
1 The Geek Stuff
2 The Geek Stuff
3 The Geek Stuff
4 The Geek Stuff
5 The Geek Stuff

In the following example, we are starting from 3 and looping through upto 6. So, this will loop through: 3, 4, 5 and 6

# cat upto2.rb
3.upto(6) do |i|
  puts "#{i} The Geek Stuff"
end

The following example has looped through 4 times using upto command, but starting from 3 through 6.

# ruby upto2.rb
3 The Geek Stuff
4 The Geek Stuff
5 The Geek Stuff
6 The Geek Stuff
Add your comment

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book

Comments on this entry are closed.