11

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.

Cristiano Betta
  • 247
  • 3
  • 13

2 Answers2

22

The fastest answer is: eval.

my_hash = eval(my_str_hash)
Sony Santos
  • 5,435
  • 30
  • 41
6

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.

Jürgen Strobel
  • 2,200
  • 18
  • 30