聋奶奶红宝石

时间:2016-05-23 17:37:06

标签: ruby

我正在阅读Chris Pine Ruby教程。在其中一个练习中,我必须通过让用户连续三次写“BYE”来关闭程序来扩展程序。我想更进一步,让奶奶在程序关闭前对第三个“BYE”作出回应。每次我键入“BYE”时,我都会收到两条错误消息,但程序仍然会像它应该的那样运行。错误消息是:

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

这是我的代码:

# 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

我必须改变什么才能摆脱这些错误?提前谢谢。

3 个答案:

答案 0 :(得分:1)

常量以大写字母开头,就像变量一样,唯一的例外是常量保持不变并且不会在整个程序中发生变化。在这种情况下,每当您提到'BYE'时,您都会通过添加main()来更改它。

一般来说,常量不能重新初始化,以解决您的问题,并消除将所有引用从int main(void)更改为+=1

所需的错误
BYE

答案 1 :(得分:1)

为了扩展Nabeel Amjad给出的答案,一个名字以大写字母开头的变量在Ruby中是一个“常量”。当然,Ruby是Ruby,它仍然可以重新分配这些所谓的“常量”(因为Ruby是这样的灵活方式),但是你得到一个警告,因为那不是常量 ,在大多数情况下,当你重新分配常量时,这是一个错误。

您只需将变量BYE重命名为bye(或bYEthe_number_of_times_the_user_said_bye)即可解决此问题

答案 2 :(得分:0)

这是我在做Chris'Pine练习时所做的:

       puts "Start talking to Grandma. Sometimes she can't hear, so you might need to SPEAK UP! To leave just shout 'Bye'"
talk = gets.chomp
while talk != "BYE"
    if talk == talk.downcase || talk == talk.capitalize
        puts "HUH?! SPEAK UP, SONNY!"
        talk = gets.chomp
    elsif talk == talk.upcase
        puts "NO, NOT SINCE" + " " + (1900 + rand(81)).to_s + "!"
        talk = gets.chomp
    elsif talk == "BYE"
        break
    end
end

希望这有帮助!我有这么多的乐趣......爱克里斯派恩的学习计划