Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll

- 2x 2x
- 1.75x 1.75x
- 1.5x 1.5x
- 1.25x 1.25x
- 1.1x 1.1x
- 1x 1x
- 0.75x 0.75x
- 0.5x 0.5x
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 up-
MICHAEL P
5,191 Points1 Answer
-
MICHAEL P
5,191 PointsDoes it matter if indentations for the loops "line up" for Ruby loops? I am specifically wondering about "end"
Posted by MICHAEL PMICHAEL P
5,191 Points2 Answers
-
melissa brown
4,670 Points2 Answers
-
nusunteudevina
8,806 Points3 Answers
-
Kourosh Raeen
23,733 Points1 Answer
-
Ingrid Bardales
10,616 Points2 Answers
-
Ron L
6,463 Points1 Answer
-
giob
4,006 PointsI understand all of the code from this video with one exception; what does !name.index(/\d/) accomplish? Thanks :)
Posted by giobgiob
4,006 Points2 Answers
-
PLUS
Denis Chernik
Courses Plus Student 5,351 Points4 Answers
-
Brandon Keene
7,217 PointsRandom & String#index Documentation links broken.
Posted by Brandon KeeneBrandon Keene
7,217 Points0 Answers
-
sebastien penot
3,292 Points2 Answers
View all discussions for this video
Related 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