mike mike - 6 months ago 24
Ruby Question

Deaf Grandma Ruby

I am going through the Chris Pine Ruby tutorial. In one of the exercises, I have to extend the program by making the user write "BYE" three times in a row to shut the program. I wanted to take it a step further and have Grandma respond on the third "BYE" before the program shuts down. Every time I type "BYE" i get two error messages, but the program still runs like it should aside from that. The error messages are:

DeafGrandma.rb:11: warning: already initialized constant BYE
DeafGrandma.rb:3: warning: previous definition of BYE was here


Here is my code:

# DeafGrandma

BYE = 0

while BYE < 3

puts "What do you want to say to Grandma?"
tell_grandma = gets.chomp

if tell_grandma == "BYE"
BYE += 1
end

if tell_grandma != tell_grandma.upcase
puts "HUH!? SPEAK UP, SONNY!"
else
puts "NO, NOT SINCE #{1929 + rand(22)}!"
end
end

while BYE = 3
puts "BYE BYE, SONNY!"
break
end


What must I change to get rid of these errors? Thank you in advance.

Answer

Constants start with capital letters and are just like variables, with the only exception that constants are meant to remain constant and not change throughout your program. In this case you're changing it by adding +=1 every time you mention 'BYE'.

Constants can not be reinitialized generally speaking, to fix your problem and get rid of the errors you need to change all references from BYE to bye

bye = 0

while bye < 3

    puts "What do you want to say to Grandma?"
    tell_grandma = gets.chomp

    if tell_grandma == "BYE"
        bye += 1
    end

    if tell_grandma != tell_grandma.upcase
        puts "HUH!? SPEAK UP, SONNY!"
    else
        puts "NO, NOT SINCE #{1929 + rand(22)}!"
    end  
end 

while bye = 3
    puts "BYE BYE, SONNY!"
    break
end
Comments