Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Hash transpose

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
like image 724
Dragan Cvetinovic Avatar asked Nov 12 '10 09:11

Dragan Cvetinovic


1 Answers

If you prefer inject, you can write it as

h.inject({}) do |a, (k, v)|
  v.inject(a) do |a1, (k1, v1)|
    a1[k1] ||= {}
    a1[k1][k] = v1
    a1
  end
  a
end
like image 72
Mladen Jablanović Avatar answered Oct 19 '22 12:10

Mladen Jablanović