ruby - Creating Hash of Hash from an Array of Array -


i have array:

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

i having trouble tranforming hash follow:

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

you can use default hash values create more legible inject:

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

obviously, should replace h , a, b, c variables domain terms.

bonus: if find needing 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 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} 

Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -