0

What is the difference between

10.6.to_i

and

10.6.to_int

?

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That link is no longer valid. Please clarify.
-2

There is no difference. They are synonymous.

1 Comment

to_i and to_int may give the same result for 10.6, but "42".to_i works, whereas "42".to_int raises a NoMethodError, for reasons given in kgiannakakis's link.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.