Class

Rational

Extends:

Rational implements a rational class for numbers.

A rational number is a number that can be expressed as a fraction p/q where p and q are integers and q != 0. A rational number p/q is said to have numerator p and denominator q. Numbers that are not rational are called irrational numbers. (mathworld.wolfram.com/RationalNumber.html)

To create a Rational Number:

Rational(a,b)             # -> a/b
Rational.new!(a,b)        # -> a/b

Examples:

Rational(5,6)             # -> 5/6
Rational(5)               # -> 5/1

Rational numbers are reduced to their lowest terms:

Rational(6,10)            # -> 3/5

But not if you use the unusual method "new!":

Rational.new!(6,10)       # -> 6/10

Division by zero is obviously not allowed:

Rational(3,0)             # -> ZeroDivisionError
Constants
Unify
Public Attributes
denominator
numerator
Public Methods
% Returns the remainder when this value is divided by other.
* Returns the product of this value and a.
**
** Returns this value raised to the given power.
+ Returns the addition of this value and a.
- Returns the difference of this value and a. subtracted.
/ Returns the quotient of this value and a.
<=> Standard comparison operator.
== Returns true iff this value is numerically equal to other.
abs Returns the absolute value.
coerce
divmod Returns the quotient and remainder.
hash Returns a hash code for the object.
inspect
inspect Returns a reconstructable string representation:
new This method is actually private.
new! Implements the constructor. This method does not reduce to lowest terms or check for division by zero. Therefore #Rational() should be preferred in normal use.
power! Alias for #**
power2
reduce Reduces the given numerator and denominator to their lowest terms. Use Rational() instead.
to_f Converts the rational to a Float.
to_i Converts the rational to an Integer. Not the nearest integer, the truncated integer. Study the following example carefully:
to_r Returns self.
to_s Returns a string representation of the rational number.
Comments

Have your say
Please use Textile formatting (click here for a cheat sheet). Use <code/> and <pre/> for code samples.
Click here to login with OpenID to to post comments.