Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

RCR 320: Extend Rational to play nice with floats

0 views
Skip to first unread message

dave...@gmail.com

unread,
Oct 11, 2005, 12:22:30 AM10/11/05
to
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

Joel VanderWerf

unread,
Oct 11, 2005, 12:47:40 AM10/11/05
to
dave...@gmail.com wrote:
..

> Rational("1.2e-3") #=> Rational(-3, 2500)

A typo, right?

--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407


dave...@gmail.com

unread,
Oct 11, 2005, 1:13:45 AM10/11/05
to
Joel wrote:
> > Rational("1.2e-3") #=> Rational(-3, 2500)
>
> A typo, right?

Yes. Well spotted.

irb> require 'rational_ext'
=> true
irb> Rational("1.2e-3")
=> Rational(3, 2500)

There's a working test script with a +3 in the expected result at
http://www.dave.burt.id.au/ruby/rational_ext_test.rb

Cheers,
Dave

0 new messages