RCR 320: Extend Rational to play nice with floats

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,736
Latest member
zacharyharris

Latest Threads

Top