From: Tim Pease Date: 2008-02-09T06:52:38+09:00 Subject: Re: converting strings to booleans, symbols, etc On Feb 8, 2008, at 11:51 AM, an an wrote: > Hi, > > I am parsing an xml document, and I wanted to know if there is a quick > built in way to convert a string to a symbol or a boolean. an example > xml doc would be: > > data > > Now I know I can do some string compares, and set the variable > accordingly, but I was wondering if there are shortcuts, much like the > to_i method. > Here some sample code to get your brain churning ... class String # The inverse of 'to_s' def s_ot begin return Integer(self) rescue ArgumentError (return Float(self)) rescue nil end case self when %r/^true|yes$/i; true when %r/^false|no$/i; false when %r/^nil|none$/i; nil when %r/^:\w+$/; self.tr(':','').to_sym else self end end end "1.0".s_ot #=> 1.0 (as a Float) "2".s_ot #=> 2 (as a Fixnum) "no".s_ot #=> false "none".s_ot #=> nil ":string".s_ot #=> :string (as a Symbol) Happy Friday everyone! Blessings, TwP