Talking about Linux, Ruby and other hackers' stuff.
Rational Can't Be Coerced Into BigDecimal in Ruby 1.9.3
Trying to move a rails application from ruby 1.8.7 to 1.9.3 I ran into coercion
issue of Rational class.
Ruby 1.9.3:
12345678
require'bigdecimal'require'rational'# You can multiply Rational against BigDecimalRational(1)*BigDecimal('1')# => <BigDecimal:a566d0,'0.1E1',9(36)># But you can't do the same when you change orderBigDecimal('1')*Rational(1)# => TypeError: Rational can't be coerced into BigDecimal
On other hand in Ruby 1.8.7:
12345678
require'bigdecimal'require'rational'# BigDecimal * Rational works OKBigDecimal('1')*Rational(1)# => 1.0 (Float)# But Rational * BigDecimal doesn'tRational(1)*BigDecimal('1')# => TypeError: Rational can't be coerced into BigDecimal
It’s looks weird. So I can only say for sure that Rational -> BigDecimal
coercion is not implemented in Ruby.
I’ve tried to fix it with simple monkey patch:
1234567891011
# Works only for Ruby1.9.3classRationaldefcoerce(value)casevaluewhenBigDecimalreturnself,valueelsesuperendendend