Alessandro
Alessandro

Reputation: 57

Invalid value for Integer

This code:

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]

raises an error:

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

What is the error?

Upvotes: 3

Views: 4848

Answers (4)

Ricardo Jacas
Ricardo Jacas

Reputation: 156

The error is simply telling you that you are trying to convert something that is not an integer inside an integer format.

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

Removing the spaces will generate a valid integer, in that case.

Upvotes: 1

sawa
sawa

Reputation: 168081

In line:

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

Each %d notation in the string attempts to interpret the argument passed to it by applying Integer() to it. This works for the first three arguments, which can be interpreted as an integer (my_age, my_height, my_weight). But with the fourth argument my_age + my_height + my_weight, the value is "31170 82 ", which cannot be interpreted as an integer. That is the error raised.

Upvotes: 1

Krzysiek Szymczak
Krzysiek Szymczak

Reputation: 150

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

https://ideone.com/KYWgJK

just remove '' around your int and everything works fine.

Upvotes: 0

jdno
jdno

Reputation: 4364

The problem is that you are defining your variables as strings. And using + on strings concatenates them, which is what you are seeing with 31170 82. To solve this problem, assign integer values to the variables, not strings:

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

This should be enough to make your code work properly.

Upvotes: 2

Related Questions