Skip to content

Instantly share code, notes, and snippets.

@fellix
Last active December 18, 2015 12:19
Show Gist options
  • Save fellix/5781709 to your computer and use it in GitHub Desktop.
Save fellix/5781709 to your computer and use it in GitHub Desktop.
turning a repeating decimal into fraction
class Numeric
def £(other_number)
RepeatingDecimal.new(self, other_number)
end
end
class RepeatingDecimal
attr_reader :repeating
def initialize(base, repeating)
@base = base
@repeating = repeating
@base_number = 0
if @base.is_a? Float
@base_number = "#{@base}#{@repeating}".to_f
else
@base_number = "#{@base}.#{@repeating}".to_f
end
end
def *(number)
base_calculation = @base_number
if decimal_count == 1
base_calculation = "#{@base_number}#{@repeating}".to_f
end
number = base_calculation * number
RepeatingDecimal.new(number, @repeating)
end
def -(number)
raise "Subtracts only for another RepeatingDecimal" unless number.is_a? RepeatingDecimal
raise "Unable to subtract from another base" if self.repeating != number.repeating
@base.to_i
end
def as_fraction
calculated_number = self * multiplier
calculated_number -= self
"#{calculated_number}/#{(multiplier-1)}"
end
def to_s
@base_number.to_s + "..."
end
protected
def multiplier
@multiplier ||= ("1" + ("0" * @repeating.to_s.size)).to_i
end
def decimal_count
@base_number.to_s.split('.').last.size.to_i
end
end
puts "Fraction of 0.44... = " + 0.£(4).as_fraction
puts "Fraction of 1.23999... = " + 1.23.£(9).as_fraction
puts "Fraction of 0.12398769876... = " + 0.123.£(9876).as_fraction
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment