Array TypeError: can't convert Fixnum into String

后端 未结 6 1759
半阙折子戏
半阙折子戏 2021-01-01 10:04

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         


        
相关标签:
6条回答
  • 2021-01-01 10:43

    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
    
    0 讨论(0)
  • 2021-01-01 10:46

    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.

    0 讨论(0)
  • 2021-01-01 10:55

    Haven't tried this myself, but try replacing

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

    with

    puts array2[0] + " " + array2[1].to_s
    
    0 讨论(0)
  • 2021-01-01 11:04

    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.

    0 讨论(0)
  • 2021-01-01 11:06

    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"
    
    0 讨论(0)
  • 2021-01-01 11:07

    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
    
    0 讨论(0)
提交回复
热议问题