The While Loop4:59 with Jason Seifer
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.
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
You need to sign up for Treehouse in order to download course files.Sign up