Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The key is to use <a href="http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-group_by" rel="nofollow"><code>Enumerable#group_by</code></a> to find all the rows with the same month and then add them together:</p> <pre><code>require 'date' # Simulate rows from your DB Row = Struct.new(:date,:amount) rows = DATA.read.scan(/(\S+) - (\d+)/).map do |date,amount| Row.new( Date.strptime(date,'%m/%d/%y'), amount.to_i ) end sum_by_month = rows.sort_by(&amp;:date).group_by do |row| row.date.strftime('%b/%Y') end.map do |year_and_month,sub_rows| [ year_and_month, sub_rows.map(&amp;:amount).inject(:+) ] end p sum_by_month #=&gt; [ #=&gt; ["Aug/2012", 22000], #=&gt; ["Sep/2012", 5000], #=&gt; ["Oct/2012", 76000] #=&gt; ] __END__ 08/01/12 - 10000 08/16/12 - 12000 09/13/12 - 5000 10/12/12 - 76000 </code></pre> <p>For your specific use case, you could use this like:</p> <pre class="lang-html prettyprint-override"><code>&lt;table&gt;&lt;thead&gt;&lt;tr&gt;&lt;td&gt;&lt;/td&gt; &lt;%sum_by_month.each do |month,total|%&gt; &lt;th scope="col"&gt;&lt;%=month%&gt;&lt;/th&gt; &lt;%end%&gt; &lt;/thead&gt;&lt;tbody&gt; &lt;tr&gt;&lt;th&gt;Usage:&lt;/th&gt; &lt;%sum_by_month.each do |month,total|%&gt; &lt;td&gt;&lt;%=total%&gt;&lt;/td&gt; &lt;%end%&gt;&lt;/tr&gt; &lt;/tbody&gt;&lt;/table&gt; </code></pre> <hr> <p>Alternatively, here's a more direct approach (that I do not recommend):</p> <pre><code>sum_by_month = {} last_month = nil total = nil @invoices.each do |inv| month = inv.date.strftime('%b/%Y') unless last_month==month sum_by_month[month] = total if last_month last_month = month total = 0 end total += inv.amount end # Make sure to add in the very last month sum_by_month[month] = total if last_month </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload