Ruby Loops - The While Loop
(Page 2 of 5 )
The While Loop tells the program to continue looping while a certain criteria you specify is true.
While($_ != “Stop”)
puts “Input the right code or this computer will explode:”
gets
chomp
end
If you type anything but Stop, the program will repeat itself. The only way for the program to cease exploding is to type Stop. Remember, the != operator means does not equal.
The Until Loop
Everything has to have its arch-nemesis, its polar opposite, and the While Loop is no different. Behold: The Mighty Until Loop! It works exactly like the While Loop, only in the complete opposite fashion (I'll let that settle in).
Basically, the Until Loop tells the program to continue looping until a certain criteria is met.
Until($_ ==”Stop”)
puts “This computer will explode if you enter the wrong code:”
gets
chomp
end
As with the While Loop, the program will loop until you type the word Stop. So what's the difference? There is none really, just a different thought process. Which you use is totally a matter of taste.
Iterators
Another method of creating loops is the iterator. We will touch on it briefly here.
10.times do
puts “I am the king!”
end
The above is an example of the Times Iterator, which lets you iterate code x amount of times (in the above instance, 10 times). If you execute the above code it would return the following results:
“I am the king!”
“I am the king!”
“I am the king!”
“I am the king!”
“I am the king!”
“I am the king!”
“I am the king!”
“I am the king!”
“I am the king!”
“I am the king!”
If you wish to create an infamous infinite loop, you could use the Loop Iterator:
loop do
puts “I R A DUMB PROGRAMMER!”
end
This would loop the phrase over and over again forever (or until you shut off the computer).
Next: Stop that Loop! >>
More Ruby-on-Rails Articles
More By James Payne