Q:

How to save database results to CSV in Ruby

I am returning query results from MySQL and I need to append them to a csv file. I can retrieve the data and display it successfully but am having trouble getting it written to a csv. Here is my Ruby so far.
#! /usr/bin/ruby

require 'mysql'
require 'csv'

# variables
file_path = '/Users/pierce/tmp/'

# need mysql queries here / use mysql2 calls
test_db = Mysql.new("localhost", "root", "", "db")

series_1_results = test_db.query("SELECT 'Impressions' AS label_imp,FORMAT(sum(impressions),',') AS impressions FROM table ")

series_1_results.each_hash do |f|
  puts "#{f['label_imp']}"",\"""#{f['impressions']}""\""
end

The last statement puts the correct result: Impressions,"34,017". When I remove it and include the CSV.open statement below I get the error that follows. Line 87 begins: csv <<
CSV.open("#{file_path}"'test_file.csv', "wb") do |csv|
    series_1_results.each_hash do |s1|
      csv << ["#{s1['label_imp']}","#{s1['impressions']}"]
    end
end

test_csv.rb:87:in `[]': can't convert String into Integer (TypeError)

I am running Ruby 1.9.2 and appreciate any advice you have. 

A:

With the mysql gem (mysql2 is different) you can only iterate through a mysql result set with each_hash once: after a row has been consumed mysql no longer returns it to you because it thinks you are done with it. Your first call to each_hash consumes all the rows, so when you iterate through it a second time there are no rows left and you get no output. 
If you remove your puts version of the output it should work

