我正在尝试将查询结果带到数据库并将其保存到csv文件中。这是我目前的Ruby脚本。
#! /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
我收到以下错误。第23行是date_results.each_hash行。
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>'
任何建议表示赞赏。谢谢。
答案 0 :(得分:2)
在嵌套块中,您将覆盖f
变量。相反,尝试类似:
# 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