class Fraction

Attributes

denominator[R]
numerator[R]

Public Class Methods

new(numerator:, denominator:) click to toggle source
# File lib/eman_fraction.rb, line 3
def initialize(numerator:, denominator:)
  raise InvalidFraction, 'denominator cannot be zero' if denominator.zero?

  @numerator = numerator
  @denominator = denominator
  simplify
end

Public Instance Methods

+(other) click to toggle source
# File lib/eman_fraction.rb, line 11
def +(other)
  return 0 if zeros?(other) # Don't really know how to deal with this otherwise

  self_numerator = numerator * other.denominator
  other_numerator = other.numerator * denominator
  new_fraction = self.class.new(numerator: self_numerator + other_numerator, denominator: other.denominator * denominator)

  return 0 if new_fraction.numerator.zero?

  new_fraction
end
-(other) click to toggle source
# File lib/eman_fraction.rb, line 23
def -(other)
  self_numerator = numerator * other.denominator
  other_numerator = other.numerator * denominator
  new_fraction = self.class.new(
    numerator: self_numerator - other_numerator,
    denominator: other.denominator * denominator
  )
  return 0 if new_fraction.numerator.zero?

  new_fraction
end
==(other) click to toggle source
# File lib/eman_fraction.rb, line 35
def ==(other)
  numerator == other.numerator && denominator == other.denominator
end
coerce(other) click to toggle source
# File lib/eman_fraction.rb, line 39
def coerce(other)
  [self.class.new(numerator: other.to_i, denominator: 1), self]
end
factors(number) click to toggle source
# File lib/eman_fraction.rb, line 53
def factors(number)
  (1..number).select { |x| number % x == 0 }
end
simplify() click to toggle source
# File lib/eman_fraction.rb, line 43
def simplify
  denon_factors = factors(denominator)
  num_factors = factors(numerator)
  common_factors = denon_factors & num_factors
  return if common_factors.empty?

  @numerator /= common_factors.last
  @denominator /= common_factors.last
end
zeros?(other) click to toggle source
# File lib/eman_fraction.rb, line 57
def zeros?(other)
  (other.zero? || (other.numerator.zero? && other.denominator.zero?)) &&
    (numerator.zero? && denominator.zero?)
end