Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
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.
Important!
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
.
Terms
Infinite Loop: A loop that never exits.
Code Samples
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
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up