From: dblack@... Date: 2006-08-25T09:54:06+09:00 Subject: Re: Alternative to String#to_i ? Hi -- On Fri, 25 Aug 2006, Gennady Bystritsky wrote: > > >> -----Original Message----- >> From: dblack@rubypal.com [mailto:dblack@rubypal.com] On >> Behalf Of dblack@wobblini.net >> Sent: Thursday, August 24, 2006 4:52 PM >> To: ruby-talk ML >> Subject: Re: Alternative to String#to_i ? >> >> Hi -- >> >> On Fri, 25 Aug 2006, Jeremy Lizt wrote: >> >>> Thanks to everyone for the quick response. The Integer >> suggestion works >>> great, but I'll point out one wrinkle that I encountered: >>> >>> Integer nil # => 0 >>> >>> That was a small surprise. (These zeros keep popping up when you may >>> not expect them!) My little conversion method now works >> fine and looks >>> like this: >>> >>> def string_to_i(str) >>> if str.nil? then return nil else Integer str end >>> rescue nil >>> end >> >> I can't resist: >> >> def string_to_i(str) >> Integer(str) rescue nil unless str.nil? >> end >> >> :-) > > Likewise ;-) > > def string_to_i(str) > str and Integer(str) rescue nil > end The only reason I like mine better than yours is that mine gives nil for false, whereas yours gives false. (Possibly not a big problem in practice, though :-) David -- http://www.rubypowerandlight.com => Ruby/Rails training & consultancy ----> SEE SPECIAL DEAL FOR RUBY/RAILS USERS GROUPS! <----- http://dablog.rubypal.com => D[avid ]A[. ]B[lack's][ Web]log http://www.manning.com/black => book, Ruby for Rails http://www.rubycentral.org => Ruby Central, Inc.