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
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
Here is a way to convert a FixNum expression into a string,
x=2
print (x+20).to_s + "\sbanannas"
Didn't know you could tack on the FixnNum#to_s method to those parens.
Haven't tried this myself, but try replacing
puts array2[0] + " " + array2[1]
with
puts array2[0] + " " + array2[1].to_s
The error is basically saying you cannot convert array2[1]
(the value is a number, a type Fixnum in this case) into a String type. The way you would work around this is to convert the type into a String (this is for line 9 where the error occurs):
puts array2[0] + " " + array2[1].to_s
The array2[1].to_s converts the number into a String type.
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"
you are trying to add an integer(fixnum) and a string, which is something you can't do on ruby unless you explicitly cast the integer(fixnum) to a string. in your code array2[0]
holds a string value "banannas" and array2[1]
holds an integer(fixnum) value 1. so for your code too run correctly you need too cast the value in array2[1] to a string value.
you can change your code on line 9 to this:
puts array2[0] + " " + array2[1]._s