Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array TypeError: can't convert Fixnum into String

Tags:

arrays

ruby

I am experimenting with arrays, and am reading the book "Beginning Ruby on Rails" by Steve Holzner. I made the program:

array = ['Hello', 'there', 1, 2] puts array[1] puts array[3] puts array.length array2 = Array.new puts array2.length array2[0] = "Banana" array2[1] = 6 puts array2[0] + " " + array2[1] puts array3.length 

It doesn't do much, but when i run it i get the error

arrays.rb:9:in `+': can't convert Fixnum into String (TypeError)     from arrays.rb:9 

Why do I get this error?

like image 583
Billjk Avatar asked Mar 13 '12 03:03

Billjk


2 Answers

You can't add a string and a integer (Fixnum), in this case you tried to add 6 to "Banana".

If on line 9 you did this:

puts array2[0] + " " + array2[1].to_s 

You would get:

"Banana 6" 
like image 158
JP Silvashy Avatar answered Sep 25 '22 06:09

JP Silvashy


array2[1] is 6, which is a Fixnum. It doesn't know how to add itself to a string (which in this case is Banana. If you were to convert it to a string, it would work just fine.

puts array2[0] + " " + array2[1].to_s 
like image 32
Marc Talbot Avatar answered Sep 26 '22 06:09

Marc Talbot