How do I reverse Hash.inspect or Array.inspect? (aka .to_s) in Ruby
I accidentally saved a Ruby hash to string in Ruby 1.9 by calling my_hash.to_s
which is equal to my_hash.inspect
. This gave me a string like this:
'{"foo"=>{"bar"=>"baz", "qux"=>"quux"}'
I now want to revert this 开发者_开发知识库back into a hash. How is this done?
I'm not looking for an explanation on other serialisation techniques, I know them. I just need a way to revert this back so I can save it the right way.
The fastest answer is: eval
.
my_hash = eval(my_str_hash)
eval it.
Of course that's not safe for arbitrary input but you said you know about serialization issues. It won't work for collections containing recursive references or other objects for which eval(x.inspect) != x.
精彩评论