Decimal to fraction in Ruby
1 2 class Float 3 def number_decimal_places 4 self.to_s.length-2 5 end 6 7 def to_fraction 8 higher = 10**self.number_decimal_places 9 lower = self*higher 10 11 gcden = greatest_common_divisor(higher, lower) 12 13 return (lower/gcden).round, (higher/gcden).round 14 end 15 16 private 17 18 def greatest_common_divisor(a, b) 19 while a%b != 0 20 a,b = b.round,(a%b).round 21 end 22 return b 23 end 24 end 25