while-and-until-loop
Objectives
Describe the
while
construct and how it implements loopingDescribe the
until
looping construct
while
while
The while
construct is a little different from the loop construct that we looked at earlier. The while
construct will keep executing a block as long as a specific condition is true
.
Let's look at a long and repetitiously-counting code that uses if
statements to count from 0
to 20
and outputs "The current number is less than 20." if so. Well, we can refactor that into simple, readable, short code with the while
construct:
Think about the above code like this:
While it is true that the variable
counter
is set to a value that is less than20
, execute the code in the block.Inside the block,
puts
a phrase, and increment the counter by one.Go back to the top! Check to see if the
counter
is less than20
. If it is true that the value is less than20
, go back into the block. Otherwise, break out of the loop and don't execute the code inside the loop.
We can achieve all of that with just a few lines of code utilizing a while
construct. Go ahead and copy and paste the above code in irb.
Examples
Basic while
Example: Hot Dog Eating Contest
while
Example: Hot Dog Eating ContestLet's say you are a world famous competitive eater participating in the Coney Island Nathan's Hot Dog Eating Contest in Brooklyn, NY. You're kind of new to the competitive eating game though, so you only have the capacity for seven (7) hot dogs.
until
until
Until
is simply the inverse of a while
loop. An until
keyword will keep executing a block until a specific condition is true. In other words, the block of code following until
will execute while the condition is false. One helpful way to think about it is to read until
as "if not".
The counter once again starts at
0
. If it is not true that the counter is equal to20
, the program will execute the code in the block.Inside the block, we will
puts
a phrase and increment the counter by1
.Then, the program will go back to the top of the
until
loop and once again check to see if the counter is equal to20
. If it is not true that the counter is equal to20
, then the program will continue executing the code in the block. Otherwise, the program will break out of the loop.
Last updated