This website uses cookies. If you continue to use this site we will assume that you are happy with this. When you close this box we will save this information in a cookie to ensure you'll never be bothered with this information box. ×


For Loop

The for loop in Ruby looks almost like the same loop in the Shell. The syntax looks familiar:

for variable in enumerable [do]
  statements
end

Keyword do is optional if there is a newline after enumerable, use it only for one-liners.
The enumerable is any expression which return object of class Enumerable. Enumerables are arrays, hashes, ranges, and you can even make your own enumerable object: we will describe it later.

for i in 1..10                              # iterations on Range
  for j in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  # and on Array
    puts "#{i} * #{j} = #{i*j}"
  end
end

http_codes = {not_found: 404, ok: 200}      # iterations on Hash
for key, value in http_codes
  puts "Code for #{key} is #{value}"
end


While Loop

While loop is for running the block of code while some expression evaluates to true. Syntax:

while expression [do]
  statements
end

As you probably guess, keyword do is optional and must be used only when you write your loop in one line.
You can use while loop as a modifier, just like if, after the statement. This is handy if you have only one statement to repeat. Both example below will add spaces to the end of the string until its length reaches 10.

str = 'hello'
while str.length < 10     # this loop will repeat while length of the string is less than 10
  puts "Still increasing"
  str << " "              # add space at the end of the string
end

str = 'hello'
str << " " while str.length < 10  # while loop as a modifier


Until Loop

Until statement creates the loop, which repeats while condition is false. This is a kind opposite to while loop, but the syntax is the similar:

until expression do
  statements
end

Like the other statements it is possible to use until loop as a modifier, in one line statements.

str = 'hello'
until str.length == 10     # this loop will repeat until the length of the string reaches 10
  puts "Still increasing"
  str << " "               # add space at the end of the string
end

str = 'hello'
str << " " until str.length == 10  # until loop as a modifier