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?
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"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With