RCR 320: Extend Rational to play nice with floats

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

...

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

A typo, right?

···

dave.burt@gmail.com wrote:

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

Joel wrote:

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

A typo, right?

Yes. Well spotted.

require 'rational_ext'

=> true

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