From b200fd21bf1e8ed822d068f019812a4ff148fc9f Mon Sep 17 00:00:00 2001 From: Andrew DeMaria Date: Sat, 11 May 2013 10:54:37 -0600 Subject: [PATCH] Added separate regexes for fractions, single and mixed and beefed up the recognition of those fractions --- lib/fractional.rb | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/lib/fractional.rb b/lib/fractional.rb index 7859841..dab16e6 100644 --- a/lib/fractional.rb +++ b/lib/fractional.rb @@ -1,6 +1,9 @@ require 'rational' class Fractional + @@fractions = /^\s*\-?(?:(\d*)\s+)?(\d+)\/(\d+)\s*$/ + @@single_fraction = /^\s*(\-?\d+)\/(\d+)\s*$/ + @@mixed_fraction = /^\s*(\-?\d*)\s+(\d+)\/(\d+)\s*$/ def initialize(value) @value = value @@ -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 @@ -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)