maryanne maryanne - 7 months ago 21
Ruby Question

gets.chomp three times in a row to exit

The task is taken from "Learn to Program" by Chrise Pine. The program is called 'Deaf Grandma'. Here's the task: "whatever you type, grandma (the program) should respond with this:

`HUH?! SPEAK UP, SONNY!`


unless you shout it (type in all capitals). In this case she responds with:

`NO, NOT SINCE 1938!`


Have Grandma shout a different year each time, maybe any year at random between 1930 and 1950. You have to shout BYE three times in a row. Make sure to test your program: if you shout
BYE three times but not in a row, you should still be talking to
Grandma."
Now, everything looks fine to me, except I didn't get where to put
gets.chomp
3 times to exit a program. Eventually, I came up with this:

speak = gets.chomp
while speak != 'BYE'
puts 'HUH?! SPEAK UP, SONNY!'
if speak == speak.upcase
puts 'NO, NOT SINCE ' + (1930 + rand(20)).to_s + '!'
else repeat = gets.chomp
end
end


But in this case if I type
BYE
grandma still asks me:

`HUH?! SPEAK UP, SONNY!`


My question is: how can I properly make the program exit after I type
BYE
three times in a row?

Answer

Have a look at this, I've made some changes though. But should give you the expected output.

bye_count = 0
while true
  speak = gets.chomp
  if speak == 'BYE'
    bye_count +=1
    bye_count == 3 ? break : next
  end
  bye_count = 0 # Resets count
  if speak == speak.upcase
    puts 'NO, NOT SINCE ' + (1930 + rand(20)).to_s + '!'
  else
    puts 'HUH?! SPEAK UP, SONNY!'
  end
end