Ruby difference between whole methods

What's the difference between

10.6.to_i

      

and

10.6.to_int

      

?

0


a source to share


2 answers


This is perfectly explained here :

First of all, neither to_i nor to_int should do anything nicer than the other. Typically, these 2 methods are not very different in their implementation, they differ only in what they declare to the outside world. The to_int method is commonly used with conditionals and should be understood as follows: "Can this object be considered a valid integer at all times?"



The to_i method is commonly used for the actual conversion, and should be understood like this: "Give me the most accurate integer representation of this object"

String, for example, is a class that implements to_i but does not implement to_int. This makes sense because a string cannot be treated as a whole on its own. However, in some cases it can be represented in integer form. If we write x = "123", we can do x.to_i very well and continue with the resulting Fixnum instance, but it only worked because the characters in x could be converted to a numeric value. What if we wrote: x = "the horse outside is funny"? That's right, a string just can't be considered an integer all the time.

+6


a source


There is no difference. They are synonymous.



-2


a source







All Articles