Class: Math::Fraction

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

Instance Method Summary collapse

Constructor Details

#initialize(float, maxden = 0x100) ⇒ Fraction

Returns a new instance of Fraction.



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/frac.rb', line 32

def initialize(float, maxden = 0x100)
  if float.is_a?(String)
    @r = 0
    sign = 1
    float.split(' ', 2).each do |part|
      if (part.include?("/"))
        @r += sign * Rational(*(part.split('/', 2).map(&method(:Integer))))
      else
        @r += Math.frac(part, maxden)
        sign = @r >= 0 ? 1 : -1
      end
    end
  else
    @r = Math.frac(float, maxden)
  end
end

Instance Method Details

#to_aObject



49
50
51
52
53
# File 'lib/frac.rb', line 49

def to_a
  i = @r.to_i
  sign = i >= 0 ? 1 : -1
  [ i, (@r.numerator - i * @r.denominator) * sign, @r.denominator ]
end

#to_fObject



59
60
61
# File 'lib/frac.rb', line 59

def to_f
  @r.to_f
end

#to_rObject



55
56
57
# File 'lib/frac.rb', line 55

def to_r
  @r
end

#to_sObject



63
64
65
66
67
68
69
70
71
72
# File 'lib/frac.rb', line 63

def to_s
  n = to_a
  if n[1] == 0
    n[0].to_s
  elsif n[0] == 0
    "#{n[1]}/#{n[2]}"
  else
    "#{n[0]} #{n[1]}/#{n[2]}"
  end
end