Question

I have the following ruby hash:

 h = { i1: { q1: 1, q2:2 }, i2: { q1: 3, q2: 4} }

and I want to transpose it as follows:

{ q1: { i1: 1, i2: 3 }, q2: { i1: 2, i2: 4 } }

Now, I came up with a function that does what I want, but I wonder if there is a more succinct/elegant way for the same thing?

My solution:

 ht = Hash.new{ |h,k| h[k] = {} }

 h.each_pair do |k,ih| 
   ih.each_pair{ |ik, iv| ht[ik][k] = iv }
 end
Was it helpful?

Solution

If you prefer inject, you can write it as

h.inject({}){|a,(k,v)|
  v.inject(a){|a1,(k1,v1)|
    a1[k1] ||= {}
    a1[k1][k] = v1
    a1
  }
  a
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top