Ruby -- convert a nested hash to a multidimensional array -




i have hash named h. want store contents in multidimensional array named ar. getting error no implicit conversion nil integer.

here code:

h = {"bob" => {email: "abc" , tel: "123"} , "daisy" => {email: "cab" , tel: "123456"}}  keys = h.keys  l = h.length   ar = array.new(l) { array.new(3) }  in 0..l-1   ar[[2][i]] = keys[i]   ar[[1][i]] = h[keys[i]][:email]   ar[[0][i]] = h[keys[i]][:tel] end  puts ar.to_s 

the desired output is:

[[email_1, email_2, ..][tel_1, tel_2, ..][name_1, name_2, ..]] 

for example:

[["abc", "cab"] , ["123", "123456"] , ["bob", "daisy"]] 

this way handle this:

h.values.each_with_object({}) |h,obj|   obj.merge!(h) { |_k,v1,v2| ([v1] << v2).flatten } end.values << h.keys #=> [["abc", "cab"], ["123", "123456"], ["bob", "daisy"]] 
  • first grab values (as hashes)
  • loop through them accumulator ({})
  • merge! values accumulator , on conflict append them array
  • return values accumulator
  • then append original keys

this less explicit @mudasobwa's answer , relies on order of first value determine output. e.g. if :tel came before :email first 2 elements have reversed order





wiki

Comments

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

python - Read npy file directly from S3 StreamingBody -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -