关于ruby“得到”的问题

我想知道为什么当我试图得到不同的输入它忽略了我的第二个输入。

#!/usr/bin/env ruby #-----Class Definitions---- class Animal attr_accessor :type, :weight end class Dog < Animal attr_accessor :name def speak puts "Woof!" end end #------------------------------- puts puts "Hello World!" puts new_dog = Dog.new print "What is the dog's new name? " name = gets puts print "Would you like #{name} to speak? (y or n) " speak_or_no = gets while speak_or_no == 'y' puts puts new_dog.speak puts puts "Would you like #{name} to speak again? (y or n) " speak_or_no = gets end puts puts "OK..." gets 

正如你所看到的,它完全忽略了我的while语句。

这是一个示例输出。

 Hello World! What is the dog's new name? bob Would you like bob to speak? (y or n) y OK... 

问题是您在输入中获得了来自用户的换行符。 当他们进入“y”时你实际上得到了“y \ n”。 您需要使用字符串上的“chomp”方法关闭换行符,以使其按预期工作。 就像是:

 speak_or_no = gets speak_or_no.chomp! while speak_or_no == "y" #..... end 

一旦你使用gets()…打印那个字符串..使用p(str)通常字符串最后会有\ n .. chomp! 方法应该用来删除它…