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 conditional will exit a loop. A loop will run forever until the condition to exit the loop returns the value of true. If the condition returns the value of false, the loop will not exit. If the condition never returns true, we'll create an infinite loop.
Links
Code Samples
Random number guessing program:
loop_conditional.rb
random_number = Random.new.rand(5)
loop do
print "Guess the number between 0 and 5 (e to exit): "
answer = gets.chomp
if answer == "e"
puts "The number was #{random_number}."
break
else
if answer.to_i == random_number
puts "You guessed correctly!"
break
else
puts "Try again."
end
end
end
Program to exit a loop when a number greater than 10 is entered:
loop_conditional_number.rb
loop do
print "Enter a number greater than 10 to exit: "
answer = gets.chomp.to_i
break if answer > 10
end
Program to loop through asking for someone's name and make sure it is formatted correctly:
def get_name
name = ""
loop do
print "Enter your name (minimum 2 characters, no numbers): "
name = gets.chomp
if name.length >= 2 && !name.index(/\d/)
break
else
puts "Name must be longer than 2 characters and not contain numbers."
end
end
return name
end
name = get_name()
puts "Hi #{name}."
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