From: Josh Cheek Date: 2010-04-14T23:58:56+09:00 Subject: Re: Method to groom a string to floating point representation --000e0cd17bc2440efb0484339d97 Content-Type: text/plain; charset=ISO-8859-1 On Wed, Apr 14, 2010 at 8:33 AM, Alex DeCaria wrote: > Josh Cheek wrote: > > This is what I have so far, please check and correct any tests that > > should > > be different > > Josh, > > Your code works great! I knew there had to be a more elegant way to do > this rather than my brute force method. > > The only test it didn't seem to work on was eliminating extra + or - > signs, such as '+45-2+8' => '+4528', but now that I see what you are > doing I can probably figure out how to do that. I definitely need to > learn more about regular expressions! > > Thanks for your time and effort. > > --Alex > -- > Posted via http://www.ruby-forum.com/. > > It wasn't done, because I wanted clarification on the tests first. Anyway, this one passes all tests. def clean_string(str) str =~ /\A([-+]?)([eE]?)([^eE.]*\.?)([^eE]*)((?:[eE][+-]?)?)([^Z]*)\Z/ posneg , misplaced_e , before_dec , after_dec , e , exponent = $1 , $2 , $3 , $4 , $5 , $6 posneg + before_dec.gsub(/[^0-9.]/,'') + after_dec.gsub(/[^0-9]/,'') + e + exponent.gsub(/[^0-9]/,'') end require 'test/unit' class TestCleanString < Test::Unit::TestCase def test_delete_chars assert_equal '-24.5e45' , clean_string('-24.5fge4x5') end def test_delete_extra_decimal assert_equal '2.45' , clean_string('2.4.5') assert_equal '2.45' , clean_string('2..45') assert_equal '2.45' , clean_string('2...45') end def test_delete_extra_decimal_in_exponent assert_equal '245e76' , clean_string('245e7.6') end def test_delete_extra_or_misplaced_pos_and_neg_signs assert_equal '+4568e+45' , clean_string('+45-68+e+45-') end def test_delete_extra_or_misplaced_e_or_E assert_equal '4.67e67' , clean_string('4.67e6e-7') assert_equal '+4.67e-7' , clean_string('+e4.67e-7') end end --000e0cd17bc2440efb0484339d97--