
Loops tell our program to do something over and over; imagine hitting replay/repeat on your favorite song.
Syntax:
for [variable] in [expression]
[code]
end
Using the above syntax our program will execute our [code]
once for each element in our [expression]
. For example, if we have our expression defined as a range of 1 to 7, our for loop will execute our code 7 times, using our variable as a placeholder for each element (number) in our range as it goes through.
for i in 1..7
if i == 1
puts "I've looped 1 time!"
elsif i >= 2
puts "I've looped #{i} times!"
end
end
Here we are using i
as our variable and have our range of 1 to 7 defined for our expression. The statement for i
in 1..7
will allow i
to use the values in our range up to and including 7 and will produce the following:
I've looped 1 time!
I've looped 2 times!
I've looped 3 times!
I've looped 4 times!
I've looped 5 times!
I've looped 6 times!
I've looped 7 times!
Our above for...in
block can also be written as:
(1..7).each do |i|
if i == 1
puts "I've looped 1 time!"
elsif i >= 2
puts "I've looped #{i} times!"
end
end
This will produce the same result as above!
Why would we use one over the other then you may ask? Well, these are almost exactly the same, however, when the for...in
syntax is used it does not create a new scope for local variables. Meaning that i
would have global scope and could be called outside of our loop. This is why it is preferred that .each
is used instead; it creates a scope where our variable is only able to be called inside our loop.
For example:
for i in 1..7
if i == 1
puts "I've looped 1 time!"
elsif i >= 2
puts "I've looped #{i} times!"
end
endputs i(1..7).each do |x|
if x == 1
puts "I've looped 1 time!"
elsif i >= 2
puts "I've looped #{x} times!"
end
endputs x
These expressions would return:
I've looped 1 time!
...
I've looped 7 times!
7
I've looped 1 time!
...
I've looped 7 times!
undefined local variable or method `x`