class Math::Fraction
Public Class Methods
new(float, maxden = 0x100)
click to toggle source
# 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
Public Instance Methods
to_a()
click to toggle source
# 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_f()
click to toggle source
# File lib/frac.rb, line 59 def to_f @r.to_f end
to_r()
click to toggle source
# File lib/frac.rb, line 55 def to_r @r end
to_s()
click to toggle source
# 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