0

我有一个数组:

values = [["branding", "color", "blue"],
          ["cust_info", "customer_code", "some_customer"],
          ["branding", "text", "custom text"]]

我无法将其转换为哈希,如下所示:

{
"branding"  => {"color"=>"blue", "text"=>"custom text"},
"cust_info" => {"customer_code"=>"some customer"}
}
4

4 回答 4

3

您可以使用默认哈希值来创建比注入更清晰的内容:

h = Hash.new {|hsh, key| hsh[key] = {}}
values.each {|a, b, c| h[a][b] = c}

显然,您应该用您的领域术语替换handa, b, c变量。

奖励:如果您发现自己需要深入 N 级,请查看 autovivification:

fun = Hash.new { |h,k| h[k] = Hash.new(&h.default_proc) }
fun[:a][:b][:c][:d] = :e
# fun == {:a=>{:b=>{:c=>{:d=>:e}}}}

或者一个过于聪明的单线使用each_with_object

silly = values.each_with_object(Hash.new {|hsh, key| hsh[key] = {}}) {|(a, b, c), h| h[a][b] = c}
于 2013-08-11T00:25:03.590 回答
1

这是使用Enumerable#inject的示例:

values = [["branding", "color", "blue"],
          ["cust_info", "customer_code", "some_customer"],
          ["branding", "text", "custom text"]]

# r is the value we are are "injecting" and v represents each
# value in turn from the enumerable; here we create
# a new hash which will be the result hash (res == r)
res = values.inject({}) do |r, v|
    group, key, value = v     # array decomposition
    r[group] ||= {}           # make sure group exists
    r[group][key] = value     # set key/value in group
    r                         # return value for next iteration (same hash)
end

有几种不同的写法;我觉得上面的比较简单。请参阅从二维数组中提取并使用数组值创建散列,以使用带有“自动激活”的散列(即分组器)。

于 2013-08-10T23:51:01.283 回答
0

不太优雅但更容易理解:

hash = {}
values.each do |value|
  if hash[value[0]] 
    hash[value[0]][value[1]] = value[2]
  else
    hash[value[0]] = {value[1] => value[2]}
  end
end
于 2013-08-10T23:47:10.540 回答
0
values.inject({}) { |m, (k1, k2, v)| m[k1] = { k2 => v }.merge m[k1] || {}; m }
于 2013-08-10T23:50:15.080 回答