A loop repeats a segment of code. Ruby can repeat it indefinitely, while or until a condition changes, or once for each value in a collection. The choice determines both when the body runs and how repetition stops. section 6.2 section 6.2.3
Stop or skip an iteration
The loop method takes a code block and repeats it. For example, n = 1; loop do; n += 1; break if n > 9; end stops when n reaches 10. Use next instead of break to skip the rest of the current iteration and start another. section 6.2.1
Use while when the body should repeat while its condition is true; use until when it should repeat until its condition becomes true. A condition placed before the body can prevent any execution. With begin/end and the condition after the body, the body runs once before the first test. section 6.2.2
Listing 6.3 Using for/in with the Temperature class
class Temperature
def Temperature.c2f(celsius)
celsius * 9.0 / 5 + 32
end
end
celsius = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
puts "Celsius\tFahrenheit" #1
for c in celsius
puts "#{c}\t#{Temperature.c2f(c)}"
end
The for/in loop assigns each Celsius value from the array to c, then prints its Fahrenheit equivalent. Its body runs once per array value. section 6.2.3
The loop method is also an iterator: it repeatedly runs the block supplied with its call. An iterator can do this with yield. When the block finishes, control returns to the still-running method, which can yield again. A block belongs to the method-call syntax; it is not a normal argument. section 6.3.1 section 6.3.2
def my_loop
while true
yield
end
end
This small loop-like method uses while true to keep reaching yield, showing how repeated block execution can be built from conditional looping. section 6.3.2


























