title: Enumerating a Postgres result set in Ruby
body: <p>I can run any SQL, and get the results as a hash of columns, or rather <a href="http://deveiate.org/code/pg/PGresult.html" rel="nofollow">a set of Postgres tuples</a> (containing a hash for each tuple). </p>
  
  <p>I am unsure how to work with the Postgres result set, especially in an idiomatic Ruby-like way.</p>
  
  <p>This is my code:</p>
  
  <pre><code>sql = "select status, count(*) from batch_details where batch_id = 950 group by status"
  status_counts = ActiveRecord::Base.connection.execute(sql)
  </code></pre>
  
  <p>I have to iterate though the result set and access each element by name:</p>
  
  <pre><code>status_counts.each do |st|
    puts st
    puts st['count']
  end
  
  {"status"=&gt;"new", "count"=&gt;"2"}
  2
  {"status"=&gt;"ready", "count"=&gt;"23"}
  23
  {"status"=&gt;"processing", "count"=&gt;"177"}
  177
  {"status"=&gt;"complete", "count"=&gt;"50"}
  50
  {"status"=&gt;"error", "count"=&gt;"50"}
  50
  </code></pre>
  
  <p>It is not possible to convert the result set to an array of hashes:</p>
  
  <pre><code>2.1.1 :031 &gt; arr = status_counts.to_array
  NoMethodError: undefined method `to_array' for #&lt;PG::Result:0x000000097f17b0&gt;
  </code></pre>
  
  <p>Same thing trying to convert the result set to a hash of hashes:</p>
  
  <pre><code>2.1.1 :032 &gt; hsh = status_counts.to_hash
  NoMethodError: undefined method `to_hash' for #&lt;PG::Result:0x000000097f17b0&gt;
  </code></pre>
  
  <p>I am trying to:</p>
  
  <ul>
  <li>run a grouped by query against a (large) db</li>
  <li>determine a % processing completed by excluding some values </li>
  </ul>
  
  <p>Using the hashes above, I would like to exclude the 'new' and 'ready' statuses and add up the rest then divide by the total:</p>
  
  <pre><code>(177 + 50 + 50 / 2 + 23 + 177 + 50 + 50) * 100
  </code></pre>
  
  <p>My code so far:</p>
  
  <pre><code>status_counts.each {|st| total += st['count'].to_i} =&gt; works
  </code></pre>
  
  <p>But it doesn't work:</p>
  
  <pre><code>status_counts.each do |st|
    ['processing','complete','error'].include? st['status'] do
         total2 += st['count'].to_i
     end
  end
  
  pct = total2/total * 100
  </code></pre>
  
  <ul>
  <li>How can I work with the Postgres result sets more easily?</li>
  <li>How can I do this task in the "Ruby way"?</li>
  </ul>