ruby - Hash mapping riddle -


in ruby, how convert this:

{"1"=>{"id"=>1, "album"=>"album1", "track"=>"track1"},  "2"=>{"id"=>2, "album"=>"album1", "track"=>"track2"},  "3"=>{"id"=>3, "album"=>"album2", "track"=>"track1"},  "4"=>{"id"=>4, "album"=>"album2", "track"=>"track2"}} 

into this:

{"album1"=>   {"1"=>{"id"=>1, "album"=>"album1", "track"=>"track1"},    "2"=>{"id"=>2, "album"=>"album1", "track"=>"track2"}},  "album2"=>   {"3"=>{"id"=>3, "album"=>"album2", "track"=>"track1"},    "4"=>{"id"=>4, "album"=>"album2", "track"=>"track2"}}} 

in efficient way.

the first format itunes stores track information. last format i'd need process tracks @ level of 'album'. i've been staring @ day and, not being @ ruby, have conceded defeat. thank tutorial on hash kung-foo.


edit

while waiting moderator decide if ok, got solution:

album_tracks = {} titles = [] tracks_hash.each |album_id, album_hash|   titles << album_hash["album"] if !titles.include? album_hash["album"] end  titles.each |title|   tracks = {}   tracks_hash.each |album_id, album_hash|     tracks[album_id] = album_hash if title == album_hash["album"]   end   albums_hash[title] = tracks end 

i'm guessing there more efficient strategy involving sort of mapping doesn't require passing on entire hash twice?

your output can achieved through pretty straight-forward call group_by, followed few transforms turn results hashes:

albums = {"1"=>{"id"=>1, "album"=>"album1", "track"=>"track1"},           "2"=>{"id"=>2, "album"=>"album1", "track"=>"track2"},           "3"=>{"id"=>3, "album"=>"album2", "track"=>"track1"},           "4"=>{"id"=>4, "album"=>"album2", "track"=>"track2"}}  albums.group_by { |k,v| v['album'] }.map { |k,v| [k, v.to_h] }.to_h  # => { #  "album1"=> { #    "1"=>{"id"=>1, "album"=>"album1", "track"=>"track1"}, #    "2"=>{"id"=>2, "album"=>"album1", "track"=>"track2"} #   }, #  "album2"=>{ #    "3"=>{"id"=>3, "album"=>"album2", "track"=>"track1"}, #    "4"=>{"id"=>4, "album"=>"album2", "track"=>"track2"} #  } #} 

the key understanding methods available on enumerable translating 1 structure (ie group_by , map) , knowing ruby lets freely transform arrays hashes , vice versa.

the first, call, albums.group_by { |k,v| v['album'] }, produces correct outer hash structure, values have form [[key1, value1], [key2, value2], ...]. ruby let turn same structure {key1: value1, key2: value2} hash using to_h.


Comments

Popular posts from this blog

java - pagination of xlsx file to XSSFworkbook using apache POI -

Unlimited choices in BASH case statement -

apache - How do I stop my index.php being run twice for every user -