converting strings to booleans, symbols, etc

A

an an

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:

<test id="first" search="false">data</test>

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!
 
T

Tim Pease

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:

<test id="first" search="false">data</test>

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
 
R

Robert Klemme

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:

<test id="first" search="false">data</test>

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.

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

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top