Bharat  Bhushan
Bharat Bhushan

Reputation: 305

How to Change deep hash format based on key and values in hash of array, hash format?

I have a hash as input:

{"2"=>{"809"=>["16E", "16Es"], "954"=>["16C", "16Cs"], "955"=>["15B", "15Br"], 
 "627"=>["10B", "10Bt"]}, "1"=>{"955"=>["15C", "15Ca"], "627"=>["10C", "10Cb"]}}

and I want Output like:

{"809"=>{"2"=>["16E", "16Es"]}, "954"=>{"2"=>["16C", "16Cs"]}, 
 "955"=>{"2"=>["15B", "15Br"], "1"=>["15C", "15Ca"]}, 
 "627"=>{"2"=>["10B", "10Bt"], "1"=>["10C", "10Cb"]}}

I tried like:

{"1"=>{"627"=>["10C", "10Cb"], "955"=>["15C", "15Ca"]}, 
 "2"=>{"627"=>["10B", "10Bt"], "955"=>["15B", "15Br"], 
 "954"=>["16C", "16Cs"], 
 "809"=>["16E", "16Es"]}}.each_with_index{|item, index| hash[item]=index}

But I am not getting output as expected.

Upvotes: 0

Views: 235

Answers (2)

Ross
Ross

Reputation: 511

This should give you what you're looking for:

original_hash = {"2"=>{"809"=>["16E", "16Es"], "954"=>["16C", "16Cs"], "955"=>["15B", "15Br"], "627"=>["10B", "10Bt"]}, "1"=>{"955"=>["15C", "15Ca"], "627"=>["10C", "10Cb"]}}
original_hash.inject({}) do |hash, entry|
  entry[1].each do |k,v| 
    hash[k] ||= {}
    hash[k][entry[0]] = v 
  end
  hash
end

Output:

{"809"=>{"2"=>["16E", "16Es"]}, "954"=>{"2"=>["16C", "16Cs"]}, "955"=>{"2"=>["15B", "15Br"], "1"=>["15C", "15Ca"]}, "627"=>{"2"=>["10B", "10Bt"], "1"=>["10C", "10Cb"]}}

Upvotes: 1

Kumar Akarsh
Kumar Akarsh

Reputation: 4980

This should work:

old_hash = {"2"=>{"809"=>["16E", "16Es"], "954"=>["16C", "16Cs"], "955"=>["15B", "15Br"], "627"=>["10B", "10Bt"]}, "1"=>{"955"=>["15C", "15Ca"], "627"=>["10C", "10Cb"]}}    
new_hash = {}
old_hash.each do |key,value|
  value.each do |k,v|
    new_hash[k] = {key => v}
  end  
end

Upvotes: 2

Related Questions