【发布时间】:2012-01-26 16:34:45
【问题描述】:
我有这个字符串,我想知道如何将它转换为哈希。
"{:account_id=>4444, :deposit_id=>3333}"
【问题讨论】:
我有这个字符串,我想知道如何将它转换为哈希。
"{:account_id=>4444, :deposit_id=>3333}"
【问题讨论】:
miku 的回答中建议的方式确实是最简单且不安全。
# DO NOT RUN IT
eval '{:surprise => "#{system \"rm -rf / \"}"}'
# SERIOUSLY, DON'T
考虑使用不同的字符串表示形式的哈希值,例如JSON 或 YAML。它更安全,至少同样健壮。
【讨论】:
POST 参数作为 Ruby 对象。你怎么把它们当作一个字符串?
稍作替换,您就可以使用 YAML:
require 'yaml'
p YAML.load(
"{:account_id=>4444, :deposit_id=>3333}".gsub(/=>/, ': ')
)
但这仅适用于这个特定的简单字符串。根据您的真实数据,您可能会遇到问题。
【讨论】:
HashWithIndifferentAccess.new 以获得类似于参数哈希的哈希。
最简单且最不安全的是只评估字符串:
>> s = "{:account_id=>4444, :deposit_id=>3333}"
>> h = eval(s)
=> {:account_id=>4444, :deposit_id=>3333}
>> h.class
=> Hash
【讨论】:
如果你的字符串哈希是这样的(它可以是嵌套或普通哈希)
stringify_hash = "{'account_id'=>4444, 'deposit_id'=>3333, 'nested_key'=>{'key1' => val1, 'key2' => val2, 'key3' => nil}}"
你可以将它转换成这样的哈希值,而不需要使用危险的 eval
desired_hash = JSON.parse(stringify_hash.gsub("'",'"').gsub('=>',':').gsub('nil','null'))
对于您发布的关键是您可以像这样使用的符号的那个
JSON.parse(string_hash.gsub(':','"').gsub('=>','":'))
【讨论】:
我猜我从来没有为此发布过我的解决方法……就这样吧,
# 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("=>")}]
【讨论】:
, 或=> 的数据,这将无法正确拆分字段。 { :text => "Welcome, friends.", delim => "=>" }