I would rescue only the TypeError. Rescueing all exceptions is asking for a hard to track down bug down the road.
-Brad On Fri, Jan 22, 2010 at 11:35 AM, Glenn Little <[email protected]> wrote: > I'm looking for a simple way to check if a string really represents > a number in ruby/rails. I figured there would be a String.is_numeric? > but haven't found anything. > > I've seen suggestions for roll-your-own functions the best of which > appears to be something like (verbosely): > > def represents_number?(s) > begin > if Float(s) > return true > else > return false > end > rescue > return false > end > end > > This relies on the fact that Float() throws an exception if it > gets a string that it can't convert. > > The issue I have with this is that it feels a little hinky in > that it's relying on Float throwing an exception. Maybe that's > okay, but it feels just a shade side-effecty. > > The other option is to craft a regexp, which would be tough > if I *really* wanted to be thorough. > > Am I missing any simpler options? > > Thanks... > > -glenn > > > -- > SD Ruby mailing list > [email protected] > http://groups.google.com/group/sdruby -- SD Ruby mailing list [email protected] http://groups.google.com/group/sdruby
