D
dave.burt
Hi,
It's been a while since I extended Rational to convert nicely from
floats and strings (among other enhancements), and showed that code to
ruby-talk.
Now it's an RCR: http://www.rcrchive.net/rcr/show/320
# Rational() is backwards-compatible
Rational(1) #=> Rational(1, 1)
Rational(1, 2) #=> Rational(1, 2)
# ... but also accepts floats
Rational(1.3) #=> Rational(5854679515581645, 4503599627370496)
# ... and strings
Rational("1.3") #=> Rational(13, 10)
Rational("1.2e-3") #=> Rational(-3, 2500)
Rational("1/2") #=> Rational(1, 2)
Rational("1.5/2.3") #=> Rational(15, 23)
Rational("1.5", "2.3") #=> Rational(15, 23)
# Floats and strings have an explicit cast to_r method
"1.5/2.3".to_r #=> Rational(15, 23)
-0.25.to_r #=> Rational(-1, 4)
# You can get fractions back from the floats:
Rational(1.3).approximate #=> Rational(13, 10)
Rational(0.3333333333333).approximate #=> Rational(1, 3)
Feedback's welcome on the RCR or here.
Cheers,
Dave
It's been a while since I extended Rational to convert nicely from
floats and strings (among other enhancements), and showed that code to
ruby-talk.
Now it's an RCR: http://www.rcrchive.net/rcr/show/320
# Rational() is backwards-compatible
Rational(1) #=> Rational(1, 1)
Rational(1, 2) #=> Rational(1, 2)
# ... but also accepts floats
Rational(1.3) #=> Rational(5854679515581645, 4503599627370496)
# ... and strings
Rational("1.3") #=> Rational(13, 10)
Rational("1.2e-3") #=> Rational(-3, 2500)
Rational("1/2") #=> Rational(1, 2)
Rational("1.5/2.3") #=> Rational(15, 23)
Rational("1.5", "2.3") #=> Rational(15, 23)
# Floats and strings have an explicit cast to_r method
"1.5/2.3".to_r #=> Rational(15, 23)
-0.25.to_r #=> Rational(-1, 4)
# You can get fractions back from the floats:
Rational(1.3).approximate #=> Rational(13, 10)
Rational(0.3333333333333).approximate #=> Rational(1, 3)
Feedback's welcome on the RCR or here.
Cheers,
Dave