Search code examples
rubyabort

Can't exit loop in Deaf Grandma from Learn to Program by Chris Pine


I'm going through Learn to Program by Chris Pine and got stuck on the exercise Deaf Gradma. The purpose of the program is to have the Grandma answer HUH?! SPEAK UP, SONNY! to anything you say, except if you say something all capital (in this case she replies NO, NOT SINCE #{random year}!) or if you say BYE for three iterations in a row (in this case the program ends). So basically the program keeps going forever unless you say BYE for three consecutive iterations.

while true
  byes = 0
  say_to_grandma = gets.chomp
  if say_to_grandma == "BYE"
    byes += 1
  else
    byes = 0
  end
  if byes == 3
    abort
  end
  if say_to_grandma != say_to_grandma.upcase
    puts "HUH?! SPEAK UP, SONNY!"
  else
    random_year = rand(90) + 1926
    puts "NO, NOT SINCE #{random_year}!"
  end
end

The problem I can't solve is ending the program. I researched extensively but couldn't find a solution. I tried exit and abort but they don't work as I'd expect. Or maybe there's something wrong with my logic.


Solution

  • For the sake of giving this question an actual answer, now that the OP has figured it out, I'll explicitly state the problem:

    byes was set to 0 in the loop. That means that every iteration, no matter what you said or did, it would reset the number to 0 before prompting you to say something again. To fix this, just move that line -- byes = 0 -- to the line above the while.