【问题标题】:Question about "gets" in ruby [duplicate]关于红宝石中“获取”的问题[重复]
【发布时间】:2011-07-15 07:31:28
【问题描述】:

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

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

【问题讨论】:

标签: ruby input gets


【解决方案1】:

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

speak_or_no = gets
speak_or_no.chomp!
while speak_or_no == "y"
  #.....
end
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2011-05-23
    • 1970-01-01
    • 1970-01-01
    • 2013-01-18
    • 2016-03-23
    • 2014-01-29
    • 2014-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多