Ruby While Loop -
i created program in ruby:
print "grandma: something: " while user_input = gets.chomp #loop while getting user input case user_input when user_input.upcase puts "no, not since! " + rand(1930..1950).to_s break when user_input = 'bye' puts "good bye!" break else puts "huh?! speak up, now!" print "grandma: something: " end end
this user input , when user type upcase or bye exit program.
now issue here need change program when bye 3 times in row time exit program , not once. how can modify program that?
you need counter that's initialized outside loop, , you'll break once counter reaches 3. i've fixed case
expression well. if case
on user_input
, don't need compare user_input
in when
.
this should trick:
print "grandma: something: " bye_count = 0 while user_input = gets.chomp case user_input when user_input.upcase puts "no, not since! " + rand(1930..1950).to_s break when 'bye' bye_count += 1 if bye_count >= 3 puts 'good bye!' break end else puts "huh?! speak up, now!" print "grandma: something: " end end
Comments
Post a Comment