Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Infinite Loop

Tags:

ruby

I'm currently learning ruby, and I've gotten stuck on this problem:

Write a Deaf Grandma program. Whatever you say to grandma (whatever you type in), she should respond with HUH?! SPEAK UP, SONNY!, unless you shout it (type in all capitals). If you shout, she can hear you and yells back, NO, NOT SINCE 1938! To make your program really believable, have grandma shout a different year each time; maybe any year at random between 1930 and 1950. You can't stop talking to grandma until you shout BYE.

This is the code I tried:

puts "Say something to Grandma!"
something = gets.chomp
while something != "BYE"
    if something == something.upcase
      puts "NO, NOT SINCE 19" + (rand(30..50)).to_s + "!"
    else
      puts "HUH? SPEAK UP SONNY!"
    end
end

Whenever I execute this, the if and else strings just go on an infinite loop. What am I doing wrong here?

like image 576
user1429496 Avatar asked Nov 07 '12 22:11

user1429496


1 Answers

You are only getting the input once, you need to read it at the beginning of each loop, like so:

something=""
while something != "BYE"
    puts "Say something to Grandma!"
    something = gets.chomp
    if something == something.upcase
      puts "NO, NOT SINCE 19" + (rand(30..50)).to_s + "!"
    else
      puts "HUH? SPEAK UP SONNY!"
    end
end

Hope that makes sense.

like image 61
Will Richardson Avatar answered Oct 20 '22 23:10

Will Richardson