5

我想知道为什么当我尝试获取不同的输入时,它会忽略我拥有的第二个输入。

#!/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...
4

2 回答 2

17

问题是您从用户那里得到一个换行符。当他们输入“y”时,您实际上得到的是“y\n”。您需要使用字符串上的“chomp”方法将换行符剔除,以使其按预期工作。就像是:

speak_or_no = gets
speak_or_no.chomp!
while speak_or_no == "y"
  #.....
end
于 2011-03-14T20:30:49.993 回答
-1

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

于 2013-05-14T13:37:48.817 回答