Introduction To Ruby
The while and until statements were all examples of condition-controlled loops. For/in loops allow you to create loops which are controlled by count. This can be a more natural way to write code when the purpose of the loop is to count and repeat a specific number of times.
This example refactors the ones we used for while and until into a for/in loop. We use a range object to specify the start and end of the counting. We also use a stepper or counter variable.
for x in 1..10 do
We can use the step method with our range object to specify how we want to do the counting.
# for/in stepped
for x in (10..100).step(10) do
You can create range objects using floats too. Check out the following example,
# for/in stepped with floats
for x in (0.0..1.0).step(0.1) do
This is an interesting example. It gives you indication of the precision issues that you can get with floating point numbers,
You can create range objects for your loop using variables. This program allows the user to specify the start and end of the loop.
# for/in 4
print "Enter the start value for the loop: "
start = gets.chomp.to_i
print "Enter the end value for the loop: "
finish = gets.chomp.to_i
for i in start..finish do
- Write a program that allows a user to enter a message and the number of times that they want to repeat that message.
- Write a program to output the 8 times table.
- Write a program that lists the numbers 1 to 20 along with their squares, cubes and square roots.
- Write a program that allows the user to input 10 scores. At the end of the program, output the total, mean average, highest and lowest numbers. Remember to set the total to 0 before the loop. You will also need to establish values for your minimum and maximum variables before the loop.
- Write a program that outputs 6 random lottery numbers for the national lottery.
- Adapt the last program so that it outputs 3 sets of 6 lottery numbers. To do this, you will need to nest a loop inside a loop. Take care with your indentation so that it is clear which code belongs to which loop.