如何反转 Hash.inspect 或 Array.inspect? (又名 .to_s) 在 Ruby 中
我不小心通过调用 my_hash.to_s
(等于 my_hash.inspect
)将 Ruby 哈希保存为 Ruby 1.9 中的字符串。这给了我一个像这样的字符串:
'{"foo"=>{"bar"=>"baz", "qux"=>"quux"}'
我现在想将其恢复为哈希值。这是怎么做到的?
我不是在寻找其他序列化技术的解释,我知道它们。我只需要一种方法来恢复它,这样我就可以以正确的方式保存它。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最快的答案是:
eval
。The fastest answer is:
eval
.评估它。
当然,这对于任意输入来说并不安全,但您说您知道序列化问题。它不适用于包含递归引用的集合或 eval(x.inspect) != x 的其他对象。
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.