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
···
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:
<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.
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
···
On 08.02.2008 19:51, 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:
<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.
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
--
Posted via http://www.ruby-forum.com/\.