I have a string which looks like a hash:
"{ :key_a => { :key_1a => 'value_1a', :key_2a => 'value_2a' }, :key_b => { :key_1b => 'value_1b' } }"
How do I get a Hash out of it? like:
{ :key_a => { :key_1a => 'value_1a', :key_2a => 'value_2a' }, :key_b => { :key_1b => 'value_1b' } }
The string can have any depth of nesting. It has all the properties how a valid Hash is typed in Ruby.
The string created by calling
Hash#inspectcan be turned back into a hash by callingevalon it. However, this requires the same to be true of all of the objects in the hash.If I start with the hash
{:a => Object.new}, then its string representation is"{:a=>#<Object:0x7f66b65cf4d0>}", and I can’t useevalto turn it back into a hash because#<Object:0x7f66b65cf4d0>isn’t valid Ruby syntax.However, if all that’s in the hash is strings, symbols, numbers, and arrays, it should work, because those have string representations that are valid Ruby syntax.