views:

80

answers:

1

Okay, I'm trying to write a ruby simulation of my grandmother. I can't quite get the loop to work the way I'd like though. I want granny to respond with

"OH, THAT REMINDS ME OF BACK IN (random year) ..."

when you answer her in all caps but I also want her to respond with

"WHAT'D YOU SAY????"

when you don't use all caps. I can get each one to work separately but I can't seem to make a continuous loop of granny with her crazy responses. Here's the code:

puts 'HELLO SONNY! WHAT\'S NEW IN THE WHO\'S IT WHAT\'S IT?'
response = gets.chomp

while response == response.upcase
  puts 'OH, THAT REMINDS ME OF BACK IN ' + (rand(50) + 1905).to_s + '...'
  response = gets.chomp
end

while response != response.upcase
  puts 'WHAT\'D YOU SAY????'
  response = gets.chomp
end

Any ideas?

+6  A: 

The issue is that once you exit the first while loop, you're never returning back to it. Try something like this:

while true
  response = gets.strip
  if response == response.upcase
     puts msg1
  else
     puts msg2
  end
end

That'll run forever, until you decide to kill virtual-granny with Ctrl-C.

perimosocordiae
Great, that fixed her! Any upside to using .strip over .chomp?
585connor
I like it because it does both leading and trailing whitespace of any kind, where chomp just pulls off trailing newlines. In this case, though, you don't really need either.
perimosocordiae
"kill virtual-granny" - that's just wrong...
Andrew Grimm
You can replace `while true` with `while response = gets.strip`.
Andrew Grimm