Tim Pease
8/6/2008 4:18:00 PM
On Aug 6, 2008, at 10:03 AM, Mage wrote:
> Hello,
>
> I have a string like: ' "gaz"=>"1", "viz"=>"1", "lift"=>"0",
> "kamra"=>"1", "klima"=>"0" '
> Is it possible to convert this easily to hash without calling eval
> or writing regexp?
>
> eval is easy and unsecure. Regexp is not very simple if you want
> handle every special case (nested values etc).
>
> Mage
>
str = ' "gaz"=>"1", "viz"=>"1", "lift"=>"0", "kamra"=>"1",
"klima"=>"0" '
h = {}
str.split(',').each do |substr|
ary = substr.strip.split('=>')
h[ary.first.tr('"','')] = ary.last.tr('"','')
end
But that won't handle nested values -- that's left for someone else
with more time than me.
Blessings,
TwP