关于Ruby中的“gets”的问题

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...

有关如何调试脚本的提示,请参见https://dev59.com/VW865IYBdhLWcg3wKLT5。 - Andrew Grimm
2个回答

17

问题在于您从用户输入中获取了换行符。当他们输入"y"时,您实际上获取的是"y\n"。 您需要使用字符串的"chomp"方法去掉换行符,以使其按您的意图工作。像这样:

问题在于您从用户输入中获取了换行符。当他们输入"y"时,您实际上获取的是"y\n"。 您需要使用字符串的"chomp"方法去掉换行符,以使其按您的意图工作。像这样:

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

示例:http://rubylearning.com/satishtalim/getting_input.html - McStretch

-1

一旦使用gets()... 使用p(str)打印该字符串。 通常字符串末尾会有\n...应使用chomp!方法将其删除...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接