如何反转Hash.inspect或Array.inspect? (又名.to_s)在Ruby中

时间:2022-06-01 21:05:26

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:

我不小心通过调用my_hash.to_s(等于my_hash.inspect)将Ruby哈希保存到Ruby 1.9中的字符串。这给了我一个像这样的字符串:

'{"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.

我不是在寻找其他序列化技术的解释,我知道它们。我只需要一种方法来恢复它,所以我可以正确的方式保存它。

2 个解决方案

#1


19  

The fastest answer is: eval.

最快的答案是:eval。

my_hash = eval(my_str_hash)

#2


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.

当然,这对任意输入都不安全,但是你说你知道序列化问题。它不适用于包含递归引用的集合或eval(x.inspect)!= x的其他对象。

#1


19  

The fastest answer is: eval.

最快的答案是:eval。

my_hash = eval(my_str_hash)

#2


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.

当然,这对任意输入都不安全,但是你说你知道序列化问题。它不适用于包含递归引用的集合或eval(x.inspect)!= x的其他对象。