无法使用ruby中的STDIN.gets.chomp()获取正确的输入

时间:2012-02-11 14:11:42

标签: ruby stdin

我正在关注LearnRubyTheHardWay教程并且难以修改exercise 29。如果我定义变量(如教程中):

,一切正常
people = 100000
cats = 34
dogs = 56

但是,如果我尝试从STDIN获取变量,如:

puts "How many people are here?"
people = STDIN.gets.chomp()
puts "How many cats?"
cats = STDIN.gets.chomp()
puts "And how many dogs?"
dogs = STDIN.gets.chomp()

相等运算符返回错误结果,好像它们只使用数字的前两位数来计算结果。因此,如果我向人们输入100000000,为猫输入11,12或13,那么这些方法会返回“太多的猫......”如果我输入150000000给人和任何< 15的猫,他们返回“不是很多猫......”另外我必须修改

dogs += 5

dogs += "5"

否则我收到以下错误:在“+”中:无法将Fixnum转换为String(TypeError)

如果我保留双引号并恢复为people = 10000的东西,我会收到以下错误:在`+'中:字符串无法强制转换为Fixnum(TypeError)

所以说,我对本教程中的代码没有任何问题,只是试着了解导致STDIN方法引入错误的原因。我查看了RubyDoc.org,看看是否存在fixnum,integer或string类的问题,或者是与chomp或gets方法有关但是找不到原因的问题。我之前或之后也试过to_i和to_s但没有得到任何结果。

该文件的完整源代码如下:

puts "How many people are here?"
people = STDIN.gets
puts "How many cats?"
cats = STDIN.gets
puts "And how many dogs?"
dogs = STDIN.gets

#people = 100000
#cats = 34
#dogs = 56

puts "So, %d people, %d cats and %d dogs, huh?" % [people,cats,dogs]

if people < cats
  puts "Too many cats! The world is doomed!"
end

if people > cats
  puts "Not many cats! The world is saved!"
end

if people < dogs
  puts "The world is drooled on!"
end

if people > dogs
  puts "The world is dry!"
end

dogs += "5"
puts "Now there are #{dogs} dogs."

if people >= dogs
  puts "People are greater than or equal to dogs."
end

if people <= dogs
  puts "People are less than or equal to dogs."
end

if people == dogs
  puts "People are dogs."
end

1 个答案:

答案 0 :(得分:3)

问题是STDIN.gets返回一个字符串。因此,所有比较操作都将对字符串进行操作。例如:

people = "100000000"
cats = "11"

puts people < cats  # => true!

这是因为<将按字典顺序比较字符串(并且1000...在字母表中11之前)。在你的例子中实际上有一点使得这里发生的事情非常明显:

dogs = STDIN.gets
dogs += "5"

如果您在此输入7,则应打印出75。你看,它只是连接字符串。

如何解决这个问题?简单,只需将字符串转换为整数:

puts "How many people are here?"
people = STDIN.gets.to_i
puts "How many cats?"
cats = STDIN.gets.to_i
puts "And how many dogs?"
dogs = STDIN.gets.to_i