Module: CMDx::Coercions::Rational

Extended by:
Rational
Included in:
Rational
Defined in:
lib/cmdx/coercions/rational.rb

Overview

Converts various input types to Rational format

Handles conversion from strings, numbers, and other values to rational numbers using Ruby’s Rational() method. Raises CoercionError for values that cannot be converted to rational numbers.

Instance Method Summary collapse

Instance Method Details

#call(value, options = {}) ⇒ Rational

Converts a value to a Rational

Examples:

Convert numeric strings to rational numbers

Rational.call("3/4")     # => (3/4)
Rational.call("2.5")     # => (5/2)
Rational.call("0")       # => (0/1)

Convert numeric types to rational numbers

Rational.call(3.14)      # => (157/50)
Rational.call(2)         # => (2/1)
Rational.call(0.5)       # => (1/2)

Handle edge cases

Rational.call("")        # => (0/1)
Rational.call(nil)       # => (0/1)
Rational.call(0)         # => (0/1)

Parameters:

  • value (Object)

    The value to convert to a rational number

  • options (Hash) (defaults to: {})

    Optional configuration parameters (currently unused)

Options Hash (options):

  • :unused (Object)

    Currently no options are used

Returns:

  • (Rational)

    The converted rational number

Raises:

  • (CoercionError)

    If the value cannot be converted to a rational number



38
39
40
41
42
43
# File 'lib/cmdx/coercions/rational.rb', line 38

def call(value, options = {})
  Rational(value)
rescue ArgumentError, FloatDomainError, RangeError, TypeError, ZeroDivisionError
  type = Locale.t("cmdx.types.rational")
  raise CoercionError, Locale.t("cmdx.coercions.into_a", type:)
end