<< Back to RUBY
Ruby While, Until and For Loop Examples
Loop over ranges of numbers. See the while-loop, until-loop and other loops.While. In a program, each statement is sequentially executed. One comes after another. But a looping construct modifies the flow of control. It makes some code repeat.
Constructs. In Ruby the while-loop is one construct. Until is the while-loop's negative friend. While continues when the condition is true, "until" when false.
While example. Here we use a simple while-loop. We introduce an iteration variable—this has the identifier "I." We start this variable at 10.
And: We increment the variable by 10, while it is less than 50. We print each iteration value.
Caution: In the while-loop, we must be careful to avoid an infinite loop. The iteration variable must cause the loop to terminate.
Ruby program that uses while-loop
# The iteration variable.
i = 10
# A while-loop.
while i < 50
print "i: ", i, "\n"
# Increment.
i += 10
end
Output
i: 10
i: 20
i: 30
i: 40
Until. An until-loop keeps iterating until the condition evaluates to true. The while-loop continues until the condition is false. This is a syntax change.
Note: The until-loop has all the flaws of the while-loop. With logic, we must ensure the loop is not infinite.
Ruby program that uses until-loop
# Start at five.
index = 5
# Continued own until zero reached.
until index == 0
print "Index: ", index, "\n"
index -= 1
end
Output
Index: 5
Index: 4
Index: 3
Index: 2
Index: 1
For-loop. We use this loop to iterate over a range of numbers. We specify the iteration variable first. And then we indicate a range of numbers. This does not need to be constant.
Here: We loop over the values 0 through 5 (inclusively) and the iteration variable i is incremented by 1 after each pass.
Range: The range of numbers can have two or three periods in it. The minimum and the maximum can also be variables, not just constants.
Ruby program that uses for-loop
# Loop over values 0 through 5.
for i in 0..5
puts i
end
Output
0
1
2
3
4
5
Break. When this statement is encountered, the loop terminates. Usually loops are clearest when the end point is clearly specified in the loop condition. But sometimes this is not possible.
Tip: The break statement is often helpful in a while-true loop, which would continue infinitely unless manually stopped.
Here: The while-loop continues printing the value until the if-statement evaluates to true. Then the break statement stops the loop.
Ruby program that uses break statement
i = 0
while true
# Break loop if variable is 5 or greater.
if i >= 5
break
end
# Display variable and increment.
puts i
i += 1
end
Output
0
1
2
3
4
Next. With this keyword, we can skip to the loop's next iteration. No further statements are executed for the current one. Unlike break, next does not terminate the loop.
Here: We test the length of each string in an array. We skip to the next iteration (with next) if a length exceeds 3.
Usually: Loops that use "next" can be rewritten with an if-else construct. This makes some loops clearer. But others are clearer with next.
Ruby program that uses next
array = ["cat", "dog", "plant", "horse"]
# Loop over values 0 through 3.
for element in array
# Next iteration if length is too big.
if element.length > 3
next
end
# Display element.
puts element
end
Output
cat
dog
Redo. Loops support the redo statement. Redo terminates the current iteration, but it does not move to the next one. It restarts from the beginning of the loop, at the same iteration.
Thus: The iteration variable (in this program, "A") is not reset. After a redo, it retains the same value.
Here: This program illustrates redo. It loops over the values 0 through 3 using a for-loop.
Rand: The program generates a random number with rand. If the random number is not equal to 2, we redo the loop iteration.
UnlessCaution: Redo can lead to infinite loops. Please check that your loop correctly terminates—consider instead the "next" keyword.
Ruby program that uses redo
# Loop over values 0 through 3.
for a in 0..3
# Get random number.
i = rand 0..4
# Display iteration variable.
puts a
# Redo loop if not 2.
redo unless i == 2
# Display done after each iteration.
puts "DONE"
end
Output
0
DONE
1
1
1
1
DONE
2
2
2
2
2
2
2
2
DONE
3
3
3
DONE
Do-keyword. In looping constructs, the do-keyword is optional. It may also have more symmetry with iterator blocks, which is an advantage. Do is used in other contexts, like iterators.
Ruby program that uses do-keyword
count = 3
# Use while with optional do-keyword.
while count >= 0 do
puts(count)
# Decrement count.
count -= 1
end
Output
3
2
1
0
End statement. A loop statement must have an end to it—the end statement is required. This is also true for methods and other kinds of blocks.
Here: We find that we get a syntax error, "expecting keyword_end" when end is omitted.
Ruby program that causes syntax error
i = 0
# This loop is correct except it has no end-statement.
while i < 10
puts(i)
i += 2
Output
/test.rb:9: syntax error, unexpected end-of-input, expecting keyword_end
i += 2
^
Iterators. A while-loop can accomplish all looping tasks. But other constructs, called iterators, are also available. They improve the syntax for many loops. They reduce errors.
Yield: The yield keyword is used to implement iterators. Often we use yield within a loop, like the while-loop.
A summary. Programs handle not just single units of data, but ranges, collections of data. In loops we handle this data. Nearly every program will have loops.
Considerations. Each of these looping constructs has its pitfalls and benefits. Usually we prefer iterators over loops in Ruby programs. But each has its place.
Related Links:
- Ruby Convert Types: Arrays and Strings
- Ruby File Handling: File and IO Classes
- Ruby Regexp Match Method
- Ruby String Array Examples
- Ruby include: Array Contains Method
- Ruby Class Examples: Self, Super and Module
- Ruby DateTime Examples: require date
- Ruby 2D Array Examples
- Ruby Number Examples: Integer, Float, zero and eql
- Ruby Exception Examples: Begin and Rescue
- Top 65 Ruby Interview Questions (2021)
- Ruby on Rails Interview Questions (2021)
- Ruby String Examples (each char, each line)
- Ruby if Examples: elsif, else and unless
- Ruby Math Examples: floor, ceil, round and truncate
- Ruby Sub, gsub: Replace String
- Ruby Substring Examples
- Ruby Console: Puts, Print and stdin
- Ruby Remove Duplicates From Array
- Ruby Random Number Generator: rand, srand
- Ruby Recursion Example
- Ruby ROT13 Method
- Ruby Iterator: times, step Loops
- Ruby String Length, For Loop Over Chars
- Ruby Join Example (Convert Array to String)
- Ruby Format String Examples
- Ruby Copy Array Example
- Ruby Keywords
- Ruby Nil Value Examples: NoMethodError
- Learn Ruby Tutorial
- Ruby Method: Def, Arguments and Return Values
- Ruby Fibonacci Sequence Example
- Ruby Hash Examples
- Ruby While, Until and For Loop Examples
- Learn Ruby on Rails Tutorial
- Ruby Word Count: Split Method
- Ruby Sort Arrays (Use Block Syntax)
- Ruby Case Examples: Ranges, Strings and Regexp
- Ruby Array Examples
- Ruby Split String Examples
Related Links
Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf