Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

String#to_r #1221

Merged
merged 4 commits into from

1 participant

@locks
Collaborator

hey guys, pull requesting to get another set of eyes on my code.

@locks locks merged commit 7682101 into master
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Commits on Oct 11, 2011
  1. @locks

    String#to_r

    locks authored
    1.9 support
  2. @locks
  3. @locks

    trimming implicit self

    locks authored
  4. @locks

    Style™

    locks authored
    fixing space
This page is out of date. Refresh to see the latest.
View
18 kernel/common/string19.rb
@@ -127,6 +127,24 @@ def succ!
alias_method :next, :succ
alias_method :next!, :succ!
+
+ def to_r
+ return Rational(0,1) if empty?
+
+ clean = strip
+ numerator = clean.gsub(".", "").to_i
+ denominator = 1
+
+ if clean.match(/\d\.\d/)
+ denominator = 10**clean.split(".")[1].to_i.to_s.length
+ end
+
+ if clean.match(/\d\/\d/)
+ denominator *= clean.split("/")[1].to_i
+ end
+
+ return Rational(numerator, denominator)
+ end
##
# call-seq:
View
12 spec/tags/19/ruby/core/string/to_r_tags.txt
@@ -1,12 +0,0 @@
-fails:String#to_r returns a Rational object
-fails:String#to_r returns (0/1) for the empty String
-fails:String#to_r returns (n/1) for a String starting with a decimal _n_
-fails:String#to_r ignores trailing characters
-fails:String#to_r ignores leading spaces
-fails:String#to_r does not ignore arbitrary, non-numeric leading characters
-fails:String#to_r treats leading hypens as minus signs
-fails:String#to_r does not treat a leading period without a numeric prefix as a decimal point
-fails:String#to_r understands decimal points
-fails:String#to_r ignores underscores between numbers
-fails:String#to_r understands a forward slash as separating the numerator from the denominator
-fails:String#to_r returns (0/1) for Strings it can't parse
Something went wrong with that request. Please try again.