Converting strings to booleans, symbols, etc

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.

thanks!

On Feb 8, 2008 12:51 PM, an an [email protected] wrote:

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.

The symbol is easy, anyway:
http://www.ruby-doc.org/core/classes/String.html#M000825

Once you’re there, making a compare for true/false isn’t so much code.
But maybe someone else has a cleaner solution to that.

Ben

Day wrote:

On Feb 8, 2008 12:51 PM, an an [email protected] wrote:

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.

The symbol is easy, anyway:
class String - RDoc Documentation

Once you’re there, making a compare for true/false isn’t so much code.
But maybe someone else has a cleaner solution to that.

Ben

thanks…thats the type of stuff i was looking for…im used to java,
and I am actively tried to avoid coding Java style in ruby, but
sometimes its hard to figure out the shortcuts that ruby provides

On Feb 8, 2008, at 11:51 AM, an an wrote:

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

On 08.02.2008 19:51, an an wrote:

to_i method.
You can create yourself some. One example:

CONV = {
“false” => false,
“true” => true,
“0” => 0,
“1” => 1,

more common / important values

}

def convert(s)
x = CONV[s]

if x.nil?
x = case x
when /\A[±]?\d+\z/
s.to_i
when /\A[±]?\d+(?:.\d+)?\z/
s.to_f
# more
else
x
end
end

x
end

Kind regards

robert