Now that you are familiar with conditions, it's time to look at another
kind of loop: The while loop.
This type of loop is much more powerful than the one you've seen already.
But it requires understanding conditionals. It's basic for is:
Where cond is a condition like the ones you saw in the last
Here is a simple example:
Let's go through this program:
- Set count to 0
- Since count < 10 we go into the loop.
- Inside the loop we print a message and add 1 to count.
Now count is 1.
- Since count< 10 again we go for another loop.
This continues on until count is 10. So the output of this loop
In other words, a while loop will continue repeating the
loop while the condition is true. Hence the name while.
There are some things are easy to do with a while loop, but very
difficult with a 'n.times'.
Suppose that we want to know the highest power of 2 which is less than
1000. This is easy with a while loop:
Think about how difficult this would be using 'n.times'.
Rewrite this last program so that the computer asks for
the maximum number and the program computes the corresponding
power of two.
Run the program above, and type 1e10 as input.
If you used the String#to_i method, chances are that
"1e10" was converted to 1. Let's go to irb
to try this out.
You see, 1e10 is a Float. Thus, you have to
use String#to_f instead.