如何解析哈希的字符串表示

我有这个字符串,我想知道如何将其转换为哈希。

"{:account_id=>4444, :deposit_id=>3333}" 

在miku的答案中建议的方式确实最容易和最不安全

 # DO NOT RUN IT eval '{:surprise => "#{system \"rm -rf / \"}"}' # SERIOUSLY, DON'T 

考虑使用哈希的不同字符串表示forms,例如JSON或YAML。 它更安全,至少同样强大。

只需更换一下,您就可以使用YAML:

 require 'yaml' p YAML.load( "{:account_id=>4444, :deposit_id=>3333}".gsub(/=>/, ': ') ) 

但这只适用于这个特定的简单字符串。 根据您的实际数据,您可能会遇到问题。

如果您的字符串哈希是某种类似的东西(它可以是嵌套或普通哈希)

 stringify_hash = "{'account_id'=>4444, 'deposit_id'=>3333, 'nested_key'=>{'key1' => val1, 'key2' => val2}}" 

你可以将它转换成这样的哈希,而不使用危险的eval

 desired_hash = JSON.parse(stringify_hash.gsub("'",'"').gsub('=>',':')) 

对于你发布的那个钥匙是一个符号的人你可以这样使用

 JSON.parse(string_hash.gsub(':','"').gsub('=>','":')) 

最简单和最不安全的只是评估字符串:

 >> s = "{:account_id=>4444, :deposit_id=>3333}" >> h = eval(s) => {:account_id=>4444, :deposit_id=>3333} >> h.class => Hash 

猜猜我从来没有发布过我的解决方法…在这里,

 # strip the hash down stringy_hash = "account_id=>4444, deposit_id=>3333" # turn string into hash Hash[stringy_hash.split(",").collect{|x| x.strip.split("=>")}]