Skip to content

Commit

Permalink
Added separate regexes for fractions, single and mixed and beefed up …
Browse files Browse the repository at this point in the history
…the recognition of those fractions
  • Loading branch information
muff1nman committed May 11, 2013
1 parent fbc8d18 commit b200fd2
Showing 1 changed file with 7 additions and 4 deletions.
11 changes: 7 additions & 4 deletions lib/fractional.rb
@@ -1,6 +1,9 @@
require 'rational'

class Fractional
@@fractions = /^\s*\-?(?:(\d*)\s+)?(\d+)\/(\d+)\s*$/
@@single_fraction = /^\s*(\-?\d+)\/(\d+)\s*$/

This comment has been minimized.

Copy link
@thechrisoshow

thechrisoshow May 11, 2013

Just wondering why you decided to use class variables rather than constants?

@@mixed_fraction = /^\s*(\-?\d*)\s+(\d+)\/(\d+)\s*$/

def initialize(value)
@value = value
Expand All @@ -24,7 +27,7 @@ def self.to_f(value)
result = 0

if mixed_fraction?(value)
whole, numerator, denominator = value.scan(/(\-?\d*)\s+(\d+)\/(\d+)/).flatten
whole, numerator, denominator = value.scan(@@mixed_fraction).flatten

result = (numerator.to_f / denominator.to_f) + whole.to_f.abs

Expand Down Expand Up @@ -74,15 +77,15 @@ def self.round_to_nearest_fraction(value, to_nearest_fraction)
private

def self.fraction?(value)
value.to_s.count('/') == 1
value.is_a? String and value.match(@@fractions)
end

def self.single_fraction?(value)
fraction?(value) and !mixed_fraction?(value)
fraction?(value) and value.match(@@single_fraction)
end

def self.mixed_fraction?(value)
fraction?(value) and value.match(/\-?\d*\s+\d+\/\d+/)
fraction?(value) and value.match(@@mixed_fraction)
end

def self.get_decimal_point_value(value)
Expand Down

0 comments on commit b200fd2

Please sign in to comment.