Performance improvement in method to strip non-numeral characters from string?

I need to write a method such that when we pass on a string to it, it
returns a substring out of it. returned string is such that it
consists of numerals only. All the characters other than numerals are
stripped away.

e.g.
" 2009-05-30 10:25:15 UTC" ==> 20090530102515

I have written the following method for the same.
It seems to be working but I am looking for your suggestions /
feedback for
–> performance improvment
–> any bug that i am not able to see

def getNumeralString(istr)
x = istr.split(//)
istr = “”
x.each{|a|
if a[0] >= ‘0’[0] && a[0] <= ‘9’[0]
istr = istr +a
end
};
return istr
end

Thanks for feedback

On Jun 23, 6:37 pm, Vipin [email protected] wrote:

I need to write a method such that when we pass on a string to it, it
returns a substring out of it. returned string is such that it
consists of numerals only. All the characters other than numerals are
stripped away.

e.g.
" 2009-05-30 10:25:15 UTC" ==> 20090530102515

s.gsub(/[^0-9]/,‘’)

is more concise and probably faster

Fred

I think Fred’s nailed the solution already, but some more general
advice:

  • I’d highly recommend you read Programming Ruby (the Pickaxe book),
    either online (http://www.rubycentral.com/book/), or purchased from
    Pragmatic Programmers (Pragmatic Bookshelf: By Developers, For Developers
    ruby). Your original code looks like a classic example of “C
    programmers can program any language in C”, and learning the Ruby
    idioms will help avoid this sort of thing.

  • I’d also recommend that you work on relaxing your “speed optimizing”
    tendencies. Skimming through some of your other posts to various
    Google G. shows quite a few discussions most would describe as
    “premature optimization”. While it’s important to be a little
    concerned about performance (ie, not writing algorithms that are
    deliberately inefficient), it’s equally destructive to be too
    concerned about performance. At least at the outset, just write clear
    code. A surprising amount of the time in Ruby, clear code (Fred’s
    solution using gsub) is significantly faster than unclear code.

–Matt J.

On Jun 24, 9:18 pm, Matt J. [email protected] wrote:

  • I’d also recommend that you work on relaxing your “speed optimizing”

I have written the following method for the same.
istr = istr +a
end
};
return istr
end

Thanks for feedback

Thanks for advice, Matt. I would like to read that book as soon as i
get the time from current project.
Thanks
vipin