Files
Yukihiro "Matz" Matsumoto 1cf225dfbe mruby-rational: add comprehensive call-seq documentation for Rational methods
Added complete call-seq documentation for all Rational methods in
mrblib/rational.rb (4 methods):

## Rational Class Methods:

- inspect: returns string representation for debugging with parentheses
  format, showing the rational value in "(numerator/denominator)" form

- to_s: returns string representation in "numerator/denominator" format
  for display and conversion purposes

- <=>: spaceship operator for comparison with other numeric types,
  returns -1/0/+1 for less/equal/greater comparisons, enables Comparable
  module functionality with proper nil handling for incomparable values

## Numeric Extension Methods:

- to_r: converts any numeric value to rational representation with
  denominator of 1, part of the standard numeric conversion protocol

Co-authored-by: Atlassian Rovo Dev
2025-08-14 10:52:45 +09:00

67 lines
1.4 KiB
Ruby

class Rational < Numeric
#
# call-seq:
# rat.inspect -> string
#
# Returns the value as a string for inspection.
#
# Rational(2).inspect #=> "(2/1)"
# Rational(-8, 6).inspect #=> "(-4/3)"
# Rational(1, 2).inspect #=> "(1/2)"
#
def inspect
"(#{to_s})"
end
#
# call-seq:
# rat.to_s -> string
#
# Returns the value as a string.
#
# Rational(2).to_s #=> "2/1"
# Rational(-8, 6).to_s #=> "-4/3"
# Rational(1, 2).to_s #=> "1/2"
#
def to_s
"#{numerator}/#{denominator}"
end
#
# call-seq:
# rat <=> numeric -> -1, 0, +1, or nil
#
# Returns -1, 0, or +1 depending on whether rat is less than, equal to,
# or greater than numeric. This is the basis for the tests in the Comparable module.
# Returns nil if the two values are incomparable.
#
# Rational(2, 3) <=> Rational(2, 3) #=> 0
# Rational(5) <=> 5 #=> 0
# Rational(2, 3) <=> Rational(1, 3) #=> 1
# Rational(1, 3) <=> 1 #=> -1
# Rational(1, 3) <=> 0.3 #=> 1
#
def <=>(other)
return nil unless other.kind_of?(Numeric)
self.to_f <=> other.to_f
rescue
nil
end
end
class Numeric
#
# call-seq:
# num.to_r -> rational
#
# Returns the value as a rational.
#
# 1.to_r #=> (1/1)
# (1+2i).to_r #=> (1+2i)/1)
# nil.to_r #=> TypeError
#
def to_r
Rational(self, 1)
end
end