关于红宝石"得到"的问题

Gre*_*reg 5 ruby gets input

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

#!/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
Run Code Online (Sandbox Code Playgroud)

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

这是一个示例输出.

Hello World!

What is the dog's new name? bob

Would you like bob
 to speak? (y or n) y

OK...
Run Code Online (Sandbox Code Playgroud)

Pet*_*ete 17

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

speak_or_no = gets
speak_or_no.chomp!
while speak_or_no == "y"
  #.....
end
Run Code Online (Sandbox Code Playgroud)