On Thu, Dec 4, 2014 at 10:13 PM, Colin B.
[email protected] wrote:
…
If you really need an Integer then BigDecimal#to_i and
BigDecimal#floor seem to work.
On 12/5/14, Robert K. [email protected] wrote:
…
I’d rather use #to_int than #to_i because that is the proper method
which enforces integerness.
If you are interested in how numeric classes usually work in Ruby I
have blogged about this a looong time ago:
http://blog.rubybestpractices.com/posts/rklemme/019-Complete_Numeric_Class.html
Sorry for my delay in responding.
Yes, I agree about #to_int. I should have paid closer attention to
your blog when I read it when it first came out!
I also managed not to notice the text in later editions of Programming
Ruby on the difference between unstrict and strict conversion
functions. (In my “defence”, when I learned Ruby in the early 2000s
from the first (hard copy) edition of “Programming Ruby”, there wasn’t
a Fixnum#to_int. At least, it isn’t documented in the online version
Programming Ruby: The Pragmatic Programmer's Guide although String#to_str is
and I didn’t take the reason for that and #to_s onboard at the time.)
Just to reinforce the distinction in my mind, these make a similar
point.
http://www.rubyfleebie.com/to_i-vs-to_int/
http://globaldev.co.uk/2013/09/ruby-tips-part-2/
“Why are there two methods, to_i and to_int, in BigDecimal when they
are exactly same in terms of functionality. …”
Updated by Nobuyoshi N. over 2 years ago:
They are not specific to BigDecimal.
to_i is for explicit conversion, called by users.
to_int is for implicit conversion, called by core/libraries.
I don’t understand what’s the difference between to_s and to_str (the
same for to_i - to_int, to_a - to_ary, and so), and why we need both
method styles.
Dave T.'s reply: The short forms (to_s, to_i, etc) say “do your
best to give me a string/integer/… representation of the receiver).
The to_str longer-form methods say instead that the receiver can
effectively be viewed as a string, and ask for the string
representation. So the short forms are permissive, and the long forms
will give an error if no exact conversion exists.
Now I might remember and use the distinction!