Ruby Loops5:19 with Jason Seifer
A loop is a piece of code that will run the statements inside until some condition is met. We can use loops to do things like asking a user if they want to keep entering input until they type "done" or "no" or something similar. There are several different kinds of loops available in Ruby. We can write a loop using the "loop" keyword.
We create an infinite loop when writing code in this lesson. To exit the loop, hold the
Ctrl key and press
C. On Windows, you can also use
Ctrl + Pause/Break.
Infinite Loop: A loop that never exits.
Here is our simple loop:
loop do print "Do you want to continue? (y/n) " answer = gets.chomp.downcase end
The above code creates an infinite loop, or, a loop that never exits. To fix that, we can use the
break keyword to exit the loop.
loop do print "Do you want to continue? (y/n) " answer = gets.chomp.downcase if answer == "n" break end end
You need to sign up for Treehouse in order to download course files.Sign up