Dan Solo
Dan Solo

Reputation: 717

'+' can't convert Fixnum into String (TypeError)

I've hit upon a 'can't convert Fixnum into String (TypeError)' error and whilst it seems simple enough I'm unsure about how to get around it. I thought my logic was sound - convert the entered string variable to an integer and then carry out the basic operation - but apparently I'm missing some key bit of information.

puts 'What is your favourite number?'
favenum = gets.chomp
better = favenum.to_i + 1
puts 'Yeah '+favenum+' is nice enough but '+better+' is bigger and better by far! Think on.'    

Have tried searching for an answer but examples of the same error out there are way beyond my rudimentary ruby skills at present.

Upvotes: 16

Views: 30335

Answers (3)

Lachlan Hardy
Lachlan Hardy

Reputation: 21

Based on the tutorial you're following

puts 'Please enter your favourite number: '
number = gets.chomp
imp = number.to_i + 1
puts 'I\'d say '.to_s + imp.to_s + ' is a much better number.'

Produces the "correct" result at a beginner level.

Upvotes: 2

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230286

Ruby (unlike some other languages) does not cast objects to strings when they are operands in String#+ method. Either cast to string manually:

puts 'Yeah ' + favenum.to_s + ' is nice enough but ' + better.to_s + ' is bigger and better by far!'

or use string interpolation (note the double quotes):

puts "Yeah #{favenum} is nice enough but #{better} is bigger and better by far!"

Upvotes: 49

user1475867
user1475867

Reputation: 49

Try using string interpolation, like this:

puts "Yeah #{favenum} is nice enough but #{better} is bigger and better by far! Think on."

Upvotes: 5

Related Questions