This course will be retired on June 1, 2025.
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
The while loop is similar to the loop statement and it uses a conditional to perform the logic. However, the big difference is that the while loop continues to run as long as the conditional that is set up front continues to return true. The condition is also specified as part of the argument to the while loop.
Concepts
Iterator variable
Code Samples
Here is a simple while loop:
answer = ""
while answer != "n"
print "Do you want me to repeat this pointless loop again? (y/n) "
answer = gets.chomp.downcase
end
Example while loop with exit conditional as a number:
def print_hello(number_of_times)
i = 0
while i < number_of_times
puts "hello"
i += 1
end
end
answer = 0
while answer < 5
print "How many times do you want to print 'hello'? (Enter a number greater than 5 to exit) "
answer = gets.chomp.to_i
print_hello(answer)
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