Class: Fraction

Inherits:
Numeric
  • Object
show all
Defined in:
lib/eman_fraction.rb

Defined Under Namespace

Classes: InvalidFraction

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(numerator:, denominator:) ⇒ Fraction

Returns a new instance of Fraction.

Raises:



3
4
5
6
7
8
9
# 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

Instance Attribute Details

#denominatorObject (readonly)

Returns the value of attribute denominator.



2
3
4
# File 'lib/eman_fraction.rb', line 2

def denominator
  @denominator
end

#numeratorObject (readonly)

Returns the value of attribute numerator.



2
3
4
# File 'lib/eman_fraction.rb', line 2

def numerator
  @numerator
end

Instance Method Details

#+(other) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
# 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) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
# 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) ⇒ Object



35
36
37
# File 'lib/eman_fraction.rb', line 35

def ==(other)
  numerator == other.numerator && denominator == other.denominator
end

#coerce(other) ⇒ Object



39
40
41
# File 'lib/eman_fraction.rb', line 39

def coerce(other)
  [self.class.new(numerator: other.to_i, denominator: 1), self]
end

#factors(number) ⇒ Object



53
54
55
# File 'lib/eman_fraction.rb', line 53

def factors(number)
  (1..number).select { |x| number % x == 0 }
end

#simplifyObject



43
44
45
46
47
48
49
50
51
# 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) ⇒ Boolean



57
58
59
60
# File 'lib/eman_fraction.rb', line 57

def zeros?(other)
  (other.zero? || (other.numerator.zero? && other.denominator.zero?)) &&
    (numerator.zero? && denominator.zero?)
end