Codectionary / Developer documentation / Ruby

Rational Arithmetic

Rational stores exact fractions in reduced form. Integer numerator/denominator construction avoids the approximation introduced by floating-point division. Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.

Syntax

Rational(numerator, denominator)

Examples

Rational Arithmetic

Run as a Ruby 3.2+ script. Required libraries are named in the example; declare bundled/default gems in your Gemfile when using Bundler.

portion = Rational(1, 3) + Rational(1, 6)
puts portion
puts portion.numerator
puts portion.denominator
puts portion * 6
  1. Expected output: 1/2 1 2 3/1
  2. Adding the fractions reduces the result to one half. Multiplying by six still returns a Rational, displayed as 3/1.

Best practices

  • Keep exact ratios as Rational until an external API requires Float.
  • Reject zero denominators at input boundaries.

Runtime & versions

Ruby interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Ruby documentation

Specifications & further reading