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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With