From: Matthew Williams Date: 2008-01-29T05:55:32+09:00 Subject: Re: Assistance dynamically building a nested hash I'm trying to work with this code as we speak, I'm still a bit of a Ruby novice so I'm still getting used to the idioms involved... 7stud -- wrote: > > arr = [ > [1, "01-02-2008", 5], > [1, "01-03-2008", 10], > [2, "12-25-2007", 5], > [1, "01-04-2008", 15] > ] > I'm running .to_a on my ActiveRecord find result set which is properly making it an array. > > #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 > Once all of those methods run against my result set I don't seem to end up with the result you ended up with. I'm running the debugger against it and I'm trying to follow the path to nail down why it isn't exactly working.... My code: @actuals = Actual.find(:all, :select => 'obs_number, week_ending, labor_hours', :conditions => ["week_ending >= ? AND project_number = ? AND primary_number = ?", @week_ending, @charge.project_number, @charge.primary_number]).to_a results = Hash.new do |hash, key| hash[key] = {} end @actuals.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 After that runs I'm left with results as a single hash with no data. I'll continue with the debugging and hopefully end up with a successful result soon enough. Thanks for the responses! > 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/.