5.9. Working with Rational Values

The Rational class enables us (in many cases) to work with fractional values with “infinite” precision. It helps us only when the values involved are true rational numbers (the quotient of two integers). It won’t help with irrational numbers such as pi, e, or the square root of 2.

To create a rational number, we use the special method Rational (which is one of our rare capitalized method names, usually used for data conversion or initialization).

r = Rational(1,2)   # 1/2 or 0.5
s = Rational(1,3)   # 1/3 or 0.3333...
t = Rational(1,7)   # 1/7 or 0.14...
u = Rational(6,2)   # "same as" 3.0
z = Rational(1,0)   # error!

An operation on two rationals will typically be another rational:

r+t # Rational(9, 14) r-t # Rational(5, ...

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.