Sha256: 3d34870e850b5429bb05ee980518e194a8ae770454ebeae4a5436a183c829206

Contents?: true

Size: 1.02 KB

Versions: 3

Compression:

Stored size: 1.02 KB

Contents

# frozen_string_literal: false

# Monkey patch to add some formatting methods to Rational.
#
# @author Julian Fiander
# @since 0.1.5
class Rational
  # Converts Rational to String
  #
  # If Rational is an improper fraction, removes the integer part to convert to a mixed fraction.
  #
  # @example Mixed fraction
  #   Rational(4,3).to_simplified_s #=> "1 1/3"
  # @return [String] If less than 1, fraction. If greater than 1, a mixed fraction.
  def to_simplified_s
    if self < 1
      to_s
    else
      truncated = self.truncate
      "#{truncated} #{self - truncated}"
    end
  end

  # Converts Rational to Array
  #
  # If Rational is an improper fraction, removes the integer part to convert to a mixed fraction.
  #
  # @example Mixed fraction
  #   Rational(4,3).to_simplified_a #=> [1, Rational(1,3)]
  # @return [Array] If less than 1, fraction. If greater than 1, a mixed fraction.
  def to_simplified_a
    if self < 1
      to_s
    else
      truncated = self.truncate
      [truncated, (self - truncated)]
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
usps_flags-0.5.0 lib/rational.rb
usps_flags-0.4.1 lib/rational.rb
usps_flags-0.4.0 lib/rational.rb