本文介绍了如何将 String 对象转换为 Hash 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像散列的字符串:

I have a string which looks like a hash:

"{ :key_a => { :key_1a => 'value_1a', :key_2a => 'value_2a' }, :key_b => { :key_1b => 'value_1b' } }"

我如何从中获取哈希值?喜欢:

How do I get a Hash out of it? like:

{ :key_a => { :key_1a => 'value_1a', :key_2a => 'value_2a' }, :key_b => { :key_1b => 'value_1b' } }

字符串可以有任意深度的嵌套.它具有如何在 Ruby 中输入有效 Hash 的所有属性.

The string can have any depth of nesting. It has all the properties how a valid Hash is typed in Ruby.

推荐答案

调用Hash#inspect创建的字符串可以通过调用eval变回哈希它.然而,这要求哈希中的所有对象都如此.

The string created by calling Hash#inspect can be turned back into a hash by calling eval on it. However, this requires the same to be true of all of the objects in the hash.

如果我从散列开始 {:a =>Object.new},那么它的字符串表示就是"{:a=>#<Object:0x7f66b65cf4d0>}",我不能用eval 将其转回散列,因为 # 不是有效的 Ruby 语法.

If I start with the hash {:a => Object.new}, then its string representation is "{:a=>#<Object:0x7f66b65cf4d0>}", and I can't use eval to turn it back into a hash because #<Object:0x7f66b65cf4d0> isn't valid Ruby syntax.

然而,如果散列中的所有内容都是字符串、符号、数字和数组,它应该可以工作,因为它们具有有效的 Ruby 语法的字符串表示.

However, if all that's in the hash is strings, symbols, numbers, and arrays, it should work, because those have string representations that are valid Ruby syntax.

这篇关于如何将 String 对象转换为 Hash 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 18:15