|
28 | 28 |
|
29 | 29 | class Numeric
|
30 | 30 |
|
| 31 | + #-- |
| 32 | + # We deviate from MRI behavior here because we ensure that Fixnum op Bignum |
| 33 | + # => Bignum (possibly normalized to Fixnum) |
| 34 | + # |
| 35 | + # Note these differences on MRI, where a is a Fixnum, b is a Bignum |
| 36 | + # |
| 37 | + # a.coerce b => [Float, Float] |
| 38 | + # b.coerce a => [Bignum, Bignum] |
| 39 | + #++ |
| 40 | + |
| 41 | + def coerce(other) |
| 42 | + if other.instance_of? self.class |
| 43 | + return [other, self] |
| 44 | + end |
| 45 | + |
| 46 | + [Float(other), Float(self)] |
| 47 | + end |
| 48 | + |
| 49 | + ## |
| 50 | + # This method mimics the semantics of MRI's do_coerce function |
| 51 | + # in numeric.c. Note these differences between it and #coerce: |
| 52 | + # |
| 53 | + # 1.2.coerce("2") => [2.0, 1.2] |
| 54 | + # 1.2 + "2" => TypeError: String can't be coerced into Float |
| 55 | + # |
| 56 | + # See also Integer#coerce |
| 57 | + |
| 58 | + def math_coerce(other, error=:coerce_error) |
| 59 | + begin |
| 60 | + values = other.coerce(self) |
| 61 | + rescue |
| 62 | + if error == :coerce_error |
| 63 | + raise TypeError, "#{other.class} can't be coerced into #{self.class}" |
| 64 | + else |
| 65 | + raise ArgumentError, "comparison of #{self.class} with #{other.class} failed" |
| 66 | + end |
| 67 | + end |
| 68 | + |
| 69 | + unless Rubinius::Type.object_kind_of?(values, Array) && values.length == 2 |
| 70 | + raise TypeError, "coerce must return [x, y]" |
| 71 | + end |
| 72 | + |
| 73 | + return values[1], values[0] |
| 74 | + end |
| 75 | + private :math_coerce |
| 76 | + |
| 77 | + def redo_coerced(meth, right) |
| 78 | + b, a = math_coerce(right) |
| 79 | + a.__send__ meth, b |
| 80 | + end |
| 81 | + private :redo_coerced |
| 82 | + |
31 | 83 | def zero?
|
32 | 84 | self == 0
|
33 | 85 | end
|
|
0 commit comments