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
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 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.