【发布时间】:2023-12-06 21:22:01
【问题描述】:
我正在学习 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,对猫输入任何
dogs += 5
到
dogs += "5"
否则我会得到以下错误:in `+': can't convert Fixnum into String (TypeError)
如果我保留双引号并恢复为 people = 10000 的东西,我会收到以下错误:in `+': String can't be coerced into Fixnum (TypeError)
也就是说,我对教程中的代码没有问题,只是尝试了解导致STDIN方法引入的错误的原因。我查看了RubyDoc.org,看看它是否是fixnum、整数或字符串类或任何与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
【问题讨论】: