Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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.

like image 599
Dan Solo Avatar asked Feb 15 '13 13:02

Dan Solo


2 Answers

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!"
like image 192
Sergio Tulentsev Avatar answered Sep 20 '22 06:09

Sergio Tulentsev


Try using string interpolation, like this:

puts "Yeah #{favenum} is nice enough but #{better} is bigger and better by far! Think on."
like image 32
user1475867 Avatar answered Sep 20 '22 06:09

user1475867