Notes on Simple Loops and Iterators
Suppose cond is some condition
and code is a batch of code.
Bold words are keywords, and "each" is a method.
while cond [do]
code
end |
code while cond |
begin
code
end while cond |
until cond [do]
code
end |
code until cond |
begin
code
end until cond |
for i in 0..5 do
code
end |
(0..5).each do |i|
code
end |
(0..5).each {|i| code }
# { } with single-line iterators |
In the last three loops, the two on the right are
exactly the same,
and they define
a scope for local variables,
while the one on the left does not.
The vertical bars | i | define the loop variable.
This center and right ones are Ruby iterators.
A break terminates a loop.
Iterators from Methods on the Integer Class
5.downto(1) {|n| prints n, ".. " }
prints: 5.. 4.. 3. 2.. 1..
5.times do |i|
print i, " "
end
prints: 0 1 2 3 4
do end and { } are the same
Convention: Use { } on one line, do end multi-line
5.upto(10) {|i| print i, " " }
Iterators from Range Objects
(start .. end) and (start ... end) create Range objects
Along with each, these create an iterator:
(10..15).each do |n|
print n, ' '
end
prints: 10 11 12 13 14 15
for i in 1..3
print i, " "
end
prints: 1 2 3
for i in 1...3
print i, " "
end
prints: 1 2
Iterators from arrays
[1, 3, 5, 7].each {|i| print i, " " }
prints: 1 3 5 7
for i in [1, 3, 5, 7]
print i, " " }
end
prints: 1 3 5 7