The Ruby method each
allows you to iterate over a list of items. This is essentially a for-each style of loop and is like JavaScript’s each method.
numbers = [1, 3, 5, 7]
numbers.each { |item| puts item }
Notice that the iterative value is placed inside of two pipe (|
) characters.
You don’t have to put everything on one line. In fact, you can’t if you have multiple lines of code in your each loop.
numbers = [1, 3, 5, 7]
total = 0
numbers.each {
|item|
puts item
total += item
}
puts "The total is: " + total.to_s
Notice that total has a .to_s
method to convert the integer value to a string.
Hashes
A has in Ruby is similar to a dictionary in Python or a map in Java or Go. It is a key/value pairing, which can also be iterated over. However, with the each, define both the key and the value.
hash = { apple: 3, banana: 0.49 }
hash.each { |key,value| puts "The #{key}'s price is $#{value}" }
Note: Interestingly, in Ruby you must put a zero (0
) before a floating point number.
Notice how, between the pipes, you have both the key and the value, which are separated by a comma.
A (Non)Traditional For Loop
If you are looking to repeat an action a set number of times, there is another option. That is the times
method.
Given a number, specify .times
, and then a body.
5.times { |i| puts "hello #{i}" }
Notice how, similar to the each
method, you use the |<variable>|
to specify an iteration count. Likewise, you use braces instead of an end command to define your loop block.
Note: You can add this to a literal number. It does not have to be to a variable, altough it can be.
counter = 10
counter.times { |i| puts "hello #{i}" }
Range Loops
Like many languages, if you use times
, it starts at 0. Therefore you can use it with a range, to allow you a different starting number.
(1..5).each { |i| puts "hello #{i}" } #this prints for numbers 1 to 5
The While Loop
Ruby also has a while, or conditional loop, like most languages.
n = 1
while n <= 10
puts "Hello " + n.to_s
n += 1
end
Notice that there is no parenthesis around the while condition, similar to go. Also, instead of the braces like with the times
and each
loops, there is now the use of the end
keyword.
The Until Loop
Similar to the unless command in Ruby (a negative if), there is a conditional until
loop in Ruby that does something while the condition is false.
n = 1
until n == 10
puts "Hello " + n.to_s
n += 1
end
Repetition with Ruby was originally found on Access 2 Learn