pchu
pchu

Reputation: 181

Creating Hash of Hash from an Array of Array

I have an array:

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

I am having trouble tranforming it to hash as follow:

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

Upvotes: 0

Views: 118

Answers (4)

Cade
Cade

Reputation: 3181

You can use default hash values to create something more legible than inject:

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

Obviously, you should replace the h and a, b, c variables with your domain terms.

Bonus: If you find yourself needing to go N levels deep, check out 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}}}}

Or an overly-clever one-liner using each_with_object:

silly = values.each_with_object(Hash.new {|hsh, key| hsh[key] = {}}) {|(a, b, c), h| h[a][b] = c}

Upvotes: 3

user2246674
user2246674

Reputation: 7719

Here is an example using 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

There are several different ways to write this; I think the above is relatively simple. See extracting from 2 dimensional array and creating a hash with array values for using a Hash (i.e. grouper) with "auto vivification".

Upvotes: 1

DigitalRoss
DigitalRoss

Reputation: 146231

values.inject({}) { |m, (k1, k2, v)| m[k1] = { k2 => v }.merge m[k1] || {}; m }

Upvotes: 0

AlexQueue
AlexQueue

Reputation: 6551

Less elegant but easier to understand:

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

Upvotes: 0

Related Questions