Skip to content

Instantly share code, notes, and snippets.

@rennex
Created June 25, 2013 00:56
Show Gist options
  • Save rennex/5855067 to your computer and use it in GitHub Desktop.
Save rennex/5855067 to your computer and use it in GitHub Desktop.
# converts an arbitrary decimal number into a fraction
# returns [input, result, check] where "check" is eval(result) with floats
def frac(str); raise ArgumentError unless str =~ /\A(\d*)\.(\d+)\z/; x=($1+$2).to_i; y=10**($2.size); gcd=x.gcd(y); r="#{x/gcd}/#{y/gcd}"; return [str, r, eval(r+".0")]; end
# testing it with some random examples:
p frac("#{rand 100}.#{rand 10000}")
# => ["39.3575", "15743/400", 39.3575]
# => ["34.7117", "347117/10000", 34.7117]
# => ["41.8720", "5234/125", 41.872]
# => ["2.3295", "4659/2000", 2.3295]
# this experiment was inspired by http://thedailywtf.com/Articles/OMGWTF-Finalist-07-Rube-Goldbergs-Calculator.aspx
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment