From: Rob Biedenharn Date: 2009-05-08T07:38:30+09:00 Subject: Re: How to break this down for use in a graph? On May 7, 2009, at 10:53 AM, Michael Modic wrote: >> #\"4\", >> \"sales_day\"=>\"2009-04-13\", \"sales_rep\"=>\"Michael\"}>, >> #\"2\", >> \"sales_day\"=>\"2009-04-13\", \"sales_rep\"=>\"John\"}>, >> #\"10\", >> \"sales_day\"=>\"2009-04-13\", \"sales_rep\"=>\"Jane\"}>, >> #\"1\", >> \"sales_day\"=>\"2009-04-14\", \"sales_rep\"=>\"Michael\"}>, >> #\"9\", >> \"sales_day\"=>\"2009-04-14\", \"sales_rep\"=>\"John\"}>, >> #\"7\", >> \"sales_day\"=>\"2009-04-14\", \"sales_rep\"=>\"David\"}>, >> #\"2\", >> \"sales_day\"=>\"2009-04-14\", \"sales_rep\"=>\"Albert\"}>]" > > I forgot to put what I wanted for output. With the results above as a > sample, I want: OK, so I'll start with @results having AR model instances like the above. # First, let's make it into a simpler data structure: # a hash with keys of the sales_rep with values as an array of # [sales_day, order_count] pairs. sales_data = Hash.new {|h,k| h[k] = []} @results.each do |client| sales_data[client.sales_rep] << [client.sales_day, client.order_count] end > sales_dates = [2009-04-13, 2009-04-14] # get the unique, sorted set of dates sales_dates = sales_data.values.map{|pairs|pairs.map{|pair| pair[0]}}.flatten.uniq.sort # Perhaps you want to eliminate "holes" in the array of sales_dates # Make sure each sales_rep has the same set of entries sales_data.keys.each do |rep| sales_data[rep] = sales_dates.map do |d| if pair = sales_data[rep].assoc(d) pair[1].to_i else 0 end end end > > > Then... > > Michael, [4, 1] > John, [2, 9] > Jane, [10, 0] > David, [0, 7] > Albert, [0, 2] irb> pp sales_data {"Michael"=>[4, 1], "David"=>[0, 7], "John"=>[2, 9], "Albert"=>[0, 2], "Jane"=>[10, 0]} => nil > > > or whatever it would take for me to iterate over an array/hash of > sales_reps and call something like the following: > > for rep in sales_reps > sales_graph.add( :series, rep, [a, b] ) > end > > so that I would end up with: > sales_graph.add( :series, "Michael", [4, 1] ) > sales_graph.add( :series, "John", [2, 9] ) > sales_graph.add( :series, "Jane", [10, 0] ) > sales_graph.add( :series, "David", [0, 7] ) > sales_graph.add( :series, "Albert", [0, 2] ) > > I hope this helps. Again, any advice is greatly appreciated. > > Regards, > > Michael > > -- sales_data.each do |rep,sales| sales_graph.add(:series, rep, sales) end Assuming that you have sales_graph defined somewhere up front. -Rob Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com