Computer Science‎ > ‎

Introduction to Ruby Loops - Using While, Until, For, Break, Next , Redo, Retry



Programming With Ruby

Ruby while statement


This typically looks something like this :

while condition
   code to execute
end

For instance, suppose we need to display 1 to 5 using while. 


i = 0
while i < 5
    i += 1
    puts i
end


This will display 
1
2
3
4
5

Or, we can even try it out quickly in the Interactive Ruby Shell (irb) :


irb(main):026:0> i = 0
=> 0
irb(main):027:0> while i < 5
irb(main):028:1> i += 1
irb(main):029:1> puts i
irb(main):030:1> end
1
2
3
4
5
=> nil


Begin-End-While


Another way to use "while" is the begin-end-while group of statements.

begin
    [instructions]
end while [some condition is true]

For example, the following code, will display 1 to 6 on a new line.


begin
    i = i + 1
    puts i
end while i < 6


Output
1
2
3
4
5
6

Let's try this out in irb and here's what it looks like :

irb(main):046:0> i = 0 
=> 0
irb(main):047:0> begin 
irb(main):048:1* i = i + 1 
irb(main):049:1> puts i
irb(main):050:1> end while i < 6
1
2
3
4
5
6
=> nil


In general, 'while' executes code when the conditional is true.
There is an "until" keyword, which indicates that the corresponding code block will be executed till the condition is false.

Until modifier in Ruby


i = 0
begin
    i = i + 1
    puts i
end until i > 6

This displays :
1
2
3
4
5
6
7

When i = 7, the condition (i >6) becomes true  and so the loop terminates.


Ruby for Statement


To give you an idea of what a Ruby for loop looks like, here's a loop which displays 1 to 5
'

for counter in 1..5
    puts counter
end

The output ( 1 to 5 on new lines) :
1
2
3
4
5


A neater equivalent to the for loop (more on the lines of the foreach idea) : 


(1..5).each{ |num|
    puts num
end

The output ( 1 to 5 on new lines) :
1
2
3
4
5

Ruby break Statement

This terminates the innermost loop.


i = 1
while i > 0
    puts i
    break if i == 2
    i += 1
end

Output :
1
2
(and the loop breaks immediately after that)

Ruby next Statement

This jumps to the next immediate iteration of the innermost loop.
For example, the following loop will keep skipping to the next loop, and only proceeds beyond the next statement when i becomes 3.

for j in 0..4
   if j<2
        next
    end
    puts j
 end

Output: 
( When j = 0 and j = 1, the loop skips to the next iteration as soon as it encounters the next statement. )
2
3
4

Ruby redo Statement

Restarts the iteration of the most internal loop without checking the condition

restarted = false
for x in 1..5
    if x == 1
        if restarted == false
            puts "Re-doing when x = " + x.to_s
            restarted = true
            redo
        end
    end
    puts x
end

Trying it out in IRB ( Interactive Ruby Shell), this is what the output looks like : 

irb(main):089:0> restarted = false
=> false
irb(main):090:0> for x in 1..5
irb(main):091:1>     if x == 1
irb(main):092:2>         if restarted == false
irb(main):093:3>             puts "Re-doing when x = " + x.to_s
irb(main):094:3>             restarted = true
irb(main):095:3>             redo
irb(main):096:3>         end
irb(main):097:2>     end
irb(main):098:1>     puts x
irb(main):099:1> end
Re-doing when x = 1
1
2
3
4
5
=> 1..5



Ruby retry Statement

If an exception gets thrown, or if something goes wrong, this either restarts the loop (if it inside a for-loop or iteration) and if it happens to be in a begin-rescue-end expression it restarts from "begin"
The two forms look something like this :


begin
   # Try to do something
rescue
   retry -> An exception was thrown, start from the begin statement all over again
end



for x in 0..3
    retry if something_happened
end




Check out some of our other Ruby Tutorials :

Introduction to Ruby

 Introduction to Ruby and some playing around with the Interactive Ruby Shell (irb) Introduction to Ruby - Conditional statements and Modifiers: If-then, Unless, Case Introduction to Ruby Comments - Single and Multi-Line comments Introduction to Ruby Loops - Using While, Until, For, Break, Next , Redo, Retry
 Introduction to Ruby - Arrays - Sorting, Filtering (Select), Transforming, Multi-Dimensional Arrays Introduction to Ruby - Strings Introduction to Ruby - Making a Script Executable Introduction to Ruby - Regular Expressions, Match, Scan
 Introduction to Ruby - Computing Factorials Recursively : An Example of Recursion Introduction to Ruby - Binomial Coefficients (nCr) : An Example of Recursion Introduction to Ruby - Computing a Power Set : An Example of Recursion Introduction to Ruby - Towers of Hanoi : An Example of Recursion
 Introduction to Ruby - Strings: Substitution, Encoding, Built-In Methods 



Basic Data Structures With Ruby








Programming With Ruby

 Introduction to Ruby and some playing around with the Interactive Ruby Shell (irb)

Introduction to Ruby - Conditional statements and Modifiers: If-then, Unless, Case

Introduction to Ruby Comments - Single and Multi-Line comments

Introduction to Ruby Loops - Using While, Until, For, Break, Next , Redo, Retry

Introduction to Ruby - Arrays - Sorting, Filtering (Select), Transforming, Multi-Dimensional Arrays 

Introduction to Ruby - Strings

Introduction to Ruby - Making a Script Executable

Introduction to Ruby - Regular Expressions, Match, Scan

Introduction to Ruby - Computing Factorials Recursively : An Example of Recursion

Introduction to Ruby - Binomial Coefficients (nCr) : An Example of Recursion

Introduction to Ruby - Computing a Power Set : An Example of Recursion

Introduction to Ruby - Towers of Hanoi : An Example of Recursion

 Introduction to Ruby - Strings: Substitution, Encoding, Built-In Methods

Basic Data Structures in Ruby - Insertion Sort

Basic Data Structures in Ruby - Selection Sort

Basic Data Structures in Ruby - Merge Sort

Basic Data Structures in Ruby - Quick Sort

Functional Programming with Ruby

Basic Data Structures in Ruby - Stack

Basic Data Structures in Ruby - The Queue

Basic Data Structures in Ruby - Linked List - ( A Simple, Singly Linked List)

Basic Data Structures in Ruby - Binary Search Tree