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

发布于 2024-11-29 20:14:10 字数 284 浏览 2 评论 0原文

我不小心通过调用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

叹倦 2024-12-06 20:14:10

最快的答案是:eval

my_hash = eval(my_str_hash)

The fastest answer is: eval.

my_hash = eval(my_str_hash)
红颜悴 2024-12-06 20:14:10

评估它。

当然,这对于任意输入来说并不安全,但您说您知道序列化问题。它不适用于包含递归引用的集合或 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文