Integer的值无效

时间:2016-03-12 14:38:51

标签: ruby

此代码:

my_name = 'Alessandro Tegagni'
my_age = '31'
my_height = '170 '#cm
my_weight = '82 '#kg
my_eyes = 'Brown'
my_teeth = 'White'
my_hair = 'Brown'

puts "let is talk about %s." % my_name
puts "he is %d cm tall." % my_height
puts "he is %d kg heavy." % my_weight
puts "actually that is not too heavy."
puts "he is got %s eyes and %s hair." % [my_eyes,my_hair]
puts "his teeth are usually %s depending on the coffee or tea" % my_teeth

puts "if I add %d, %d, and %d I get %d." % [my_age,my_height,my_weight,my_age+my_height+my_weight]

引发错误:

:17:in `%': invalid value for Integer(): "31170 82 " (ArgumentError)

错误是什么?

4 个答案:

答案 0 :(得分:2)

问题在于您将变量定义为字符串。在字符串上使用+连接它们,这就是您在31170 82中看到的内容。要解决此问题,请将整数值分配给变量,而不是字符串:

my_name = 'Alessandro Tegagni'
my_age = 31
my_height = 170 #cm
my_weight = 82 #kg
my_eyes = 'Brown'
my_teeth = 'White'
my_hair = 'Brown'

这足以让您的代码正常运行。

答案 1 :(得分:0)

my_age = 31
my_height = 170 #cm
my_weight = 82 #kg

https://ideone.com/KYWgJK

只需在你的int周围删除'',一切正常。

答案 2 :(得分:0)

排队:

puts "if I add %d, %d, and %d I get %d." % [my_age,my_height,my_weight,my_age+my_height+my_weight]

字符串中的每个%d表示法都试图通过对其应用Integer()来解释传递给它的参数。这适用于前三个参数,可以解释为整数(my_agemy_heightmy_weight)。但是使用第四个参数my_age + my_height + my_weight,值为"31170 82 ",不能解释为整数。这就是提出的错误。

答案 3 :(得分:0)

错误只是告诉您您要转换的不是整数格式内的整数。

  

:17:in'%':Integer()的值无效:“ 31170 82”(ArgumentError)

在这种情况下,删除空格将生成一个有效的整数。