to_i Vs to_int

Have you ever come across an object that was implementing both to_i and to_int? Did you find that it was a little bit redundant (say yes please)? What is the difference between the 2?
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?”. This can be useful when using some ducktyping technique.

def my_method(an_obj)
      #Ok, this object can be considered like an integer!
      #some_method_int_value will take care of
      #this object!
      some_method_int_value(an_obj.to_i) #could use to_int as well
      #Ahhh... it doesn't have a direct representation in the integer
      #form. I will pass the object without touching it and
      #some_method_no_int_value will decide what to do from there

As you can see, to_int has been used in conjunction with the respond_to? method to check if the object could be considered like an integer. We’re not saying that what was contained into the object at this time could be converted to an integer. We are saying that this object can always be considered like an integer, regardless of its actual value. Big difference here.
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” (I added “please” because it is important to be polite when we talk to an interpreter).
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 its 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.
Float, on the other hand, is a class that implements to_int as well as to_i. Both of these methods return the same result but the presence of to_int announce that a float can always be treated like if it was an integer. And it’s okay, because in a sense a float always contains an integer part. By the way, if you convert a float with to_i or to_int, the float will be truncated an you will be left with the integer part only.
Note that there are other methods from other classes that have the same purpose like to_s Vs to_str and to_a Vs to_ary.

One thought on “to_i Vs to_int

Leave a Reply

Your email address will not be published. Required fields are marked *