Reputation: 183333
What is the difference between
10.6.to_i
and
10.6.to_int
?
Upvotes: 0
Views: 973
Reputation: 104168
This is excelently explained here:
First of all, neither to_i or to_int is meant to do something fancier than the other. Generally, those 2 methods don’t differ in their implementation that much, they only differ in what they announce to the outside world. The to_int method is generally used with conditional expressions and should be understood the following way : “Is this object can be considered like a real integer at all time?”
The to_i method is generally used to do the actual conversion and should be understood that way : “Give me the most accurate integer representation of this object please”
String, for example, is a class that implements to_i but does not implements to_int. It makes sense because a string cannot be seen as an integer in it’s own right. However, in some occasions, it can have a representation in the integer form. If we write x = “123″, we can very well do x.to_i and continue working with the resulting Fixnum instance. But it only worked because the characters in x could be translated into a numerical value. What if we had written : x = “the horse outside is funny” ? That’s right, a string just cannot be considered like an Integer all the time.
Upvotes: 6