Dragan Cvetinovic
Dragan Cvetinovic

Reputation: 163

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

Upvotes: 6

Views: 4176

Answers (1)

Mladen Jablanović
Mladen Jablanović

Reputation: 44090

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

Upvotes: 2

Related Questions