Reputation: 888
If I enter
1.1.coerce(1)
Fixnum
is coerced to Float
:
[1.0,1.1]
but when I try:
1.coerce(1.1)
I got:
[1.1,1.0]
Why is that?
Upvotes: 2
Views: 49
Reputation: 168139
There is a hierarchy between subclasses of numbers in the sense that an instance of one class can be converted to another class without losing information but not vice versa. The hierarchy goes (actually, the order between Rational
and Float
seems the opposite to me, and I don't know why it is like this):
Fixnum -> Bignum -> Rational -> Float -> Complex
When you have a Fixnum
and Float
, you can convert the Fixnum
instance into a Float
without losing information, so that is what is done. If Float
were to be converted to a Fixnum
, that would mean loss of information.
Upvotes: 1
Reputation: 54684
Read on: http://www.ruby-doc.org/core/Numeric.html#method-i-coerce
coerce(numeric) → array
If a numeric is the same type as num, returns an array containing numeric and num. Otherwise, returns an array with both a numeric and num represented as Float objects.
This coercion mechanism is used by Ruby to handle mixed-type numeric operations: it is intended to find a compatible common type between the two operands of the operator.
Upvotes: 1