From: 7stud -- Date: 2008-01-29T04:51:26+09:00 Subject: Re: Assistance dynamically building a nested hash Matthew Williams wrote: > I've done some searching and have found some nested hash references but > not quite enough to get me going with what I need. > > I'm looking to build a structure like so... > > actuals = {actual_id, {date => count, date => count, date => count}} > > An example would be like: > > actuals = {"1", {"01-01-2008" => 5, "01-02-2008" => 10}} > > Then I can later iterate through the hash and for each ID, get any date > associated with it an associated count. > > I'm pulling the data in with an ActiveRecord find that will return a > dozen or so records for a given id but with various dates and counts. > > So records returned could look like > > 1, "01-02-2008", 5 > 1, "01-03-2008", 10 > 2, "12-25-2007", 5 > 1, "01-04-2008", 15 > > Should result in a hash when I'm finished like so: > > actuals = > {"1",{"01-02-2008" => 5, "01-03-2008" => 10 "01-04-2008" => 15}}, > {"2",{"12-25-2007" => 5}} > > Iterating through those records is no problem... I just can't wrap my > brain around the nested hash of dates and counts for a given id. > > I'm assuming this is the appropriate and most effective data structure > for this data but I would be up for any other suggestions. > > I appreciate any responses, thanks. arr = [ [1, "01-02-2008", 5], [1, "01-03-2008", 10], [2, "12-25-2007", 5], [1, "01-04-2008", 15] ] #Create a hash where looking up a non-existent key #in the hash results in the key being created and #assigned an empty hash: results = Hash.new do |hash, key| hash[key] = {} end arr.each do |sub_arr| main_key = sub_arr[0] sub_key = sub_arr[1] #Create new key, value in sub hash: results[main_key][sub_key] = sub_arr[2] end p results --output:-- {1=>{"01-04-2008"=>15, "01-03-2008"=>10, "01-02-2008"=>5}, 2=>{"12-25-2007"=>5}} -- Posted via http://www.ruby-forum.com/.