34,333
edits
Changes
no edit summary
In the previous chapter we looked at [[Ruby While and Until Loops]] as a way to repeat a task until a particular expression evaluated to ''true'' or ''false''. In this chapter we will look at some other mechanisms for looping in a Ruby program, specifically ''for loops'' and a number of built-in methods designed for looping, specifically the ''loop'', ''upto'', ''downto'' and ''times''methods. == The Ruby for Loop == The ''for'' loop is a classic looping construct that exists in numerous other programming and scripting languages. It allows a task to be repeated a specific number of times. Ruby differs in that it it used in conjunction with ranges (see [[Ruby Ranges]] for more details). For example, we can repeat a task 8 times using the following ''for'' statement: <pre>for i in 1..8 do puts iend</pre> The above loop will result in the following output: <pre>12345678</pre> The ''do'' in the ''for'' statement is optional, unless the code is placed on a single line: <pre>for i in 1..8 do puts i end</pre> Ruby ''for'' loops can be nested: <pre>for j in 1..5 do for i in 1..5 do print i, " " endputsend</pre> The above code will result in the following output: <pre>1 2 3 4 51 2 3 4 51 2 3 4 51 2 3 4 51 2 3 4 5</pre> Also, the ''break if'' statement can be used to break out of a ''for loop'' (note that only the inner for loop is exited, if the loop is nested the outer loop will continue the looping run): <pre>for j in 1..5 do for i in 1..5 do print i, " " break if i == 2 endend</pre> resulting the the inner loop breaking each time i equal 2: <pre>1 21 21 21 21 2</pre>