Home>

I don't understand the object type conversion specification

Error message

An error will occur if the string is converted to a number. .
Why can I do it when I enter the formula?

y.to_i

`` `
Error message
String can't be coerced into Fixnum (TypeError)

Applicable source code

x = 50
y = "3"

y.to_i

p x + y

x = 50
y = "3"

p x + y.to_i

This worked without problems

Please describe what you tried for the problem here.

  • Answer # 1

    In

    y.to_i, you may have intended to convert the object pointed to byyfrom String to Integer, but the Integer object is discarded as it is. If you want to refer to that Integer byy, assign it toy.

    x = 50
    y = "3"
    y = y.to_i
    p x + y
    When you write

    variable.method, the object pointed to by the variable will not change to an object of another class. The value may change while the object is the same class.

  • Answer # 2

    ruby's type conversion does not have the function of automatically converting integer + character string
    Because x + y is in that form, it will result in an error that the type is different
    If it is x + y.to_i, it will pass because y is converted to an integer with y.to_i

    Automatic type conversion is performed for operations such as integers and real numbers whose types differ between numbers.