0

我正在尝试将查询结果保存到 db 并将它们保存到 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>'

任何建议表示赞赏。谢谢。

4

1 回答 1

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
于 2012-07-01T08:05:55.673 回答