analyticsPierce
analyticsPierce

Reputation: 3025

How to save database results to text file in Ruby

I am trying to take the results of a query to a db and save them to a csv file. Here is my current Ruby script.

#! /usr/bin/ruby

require 'rubygems'
require 'mysql'
require 'date'

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

date_results = db_con.query("SELECT CONCAT(CONVERT(date_format(dd.date, '%b-%e'),char),'\\n') AS date
FROM msd.date_dim dd LEFT OUTER JOIN msd.results cs 
    ON dd.id = cs.date_id
GROUP BY
    dd.date")

# create new xml file and insert header
open('test_trend.xml', 'w') do |f|
  date_results.each_hash do |f|
    f.puts "#{f['date']}"
  end      
end

I get the following error. Line 23 is the date_results.each_hash line.

so_test.rb:24:in `block (2 levels) in <main>': private method `puts' called for {"date"=>"Jun-12\n"}:Hash (NoMethodError)
    from /Users/pierce/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/ruby-mysql-2.9.9/lib/mysql.rb:686:in `call'
    from /Users/pierce/.rbenv/versions/1.9.2-p290/lib/ruby/gems/1.9.1/gems/ruby-mysql-2.9.9/lib/mysql.rb:686:in `each_hash'
    from so_test.rb:23:in `block in <main>'
    from so_test.rb:22:in `open'
    from so_test.rb:22:in `<main>'

Any advice is appreciated. Thanks.

Upvotes: 0

Views: 1263

Answers (1)

Chris Ledet
Chris Ledet

Reputation: 11628

In your nested blocks, you're overriding the f variable. Instead, try something like:

# create new xml file and insert header
open('test_trend.xml', 'w') do |f|
  date_results.each_hash do |hash|
    f.puts "#{hash['date']}"
  end      
end

Upvotes: 2

Related Questions