我使用的是Mac OSX版本10.8
我正在尝试以旧式方式创建CSV文件,但我的代码中存在错误。它应该创建一个包含三行的电子表格,即标题,以及它下面的两行数据:
File.open('table.csv', 'w') do |f|
f.puts.each {|line| puts line}
'Date','Open','High','Low','Close','Volume','Adj Close'
'10/8/2013','1676.22','1676.79','1655.03','1655.45','3569230000','1655.45'
'10/7/2013','1687.15','1687.15','1674.7','1676.12','2678490000','1676.12'
end
有人可以解决这个问题,以便它起作用并解释我做错了什么。
由于
答案 0 :(得分:1)
File.open('table.csv', 'w') do |csv|
csv << ["Date","Open","High","Low","Close","Volume","Adj Close"]
csv << ["10/8/2013","1676.22","1676.79","1655.03","1655.45","3569230000","1655.45"]
csv << ["10/7/2013","1687.15","1687.15","1674.7","1676.12","2678490000","1676.12"]
end
这应该有效。你不需要数组。
答案 1 :(得分:0)
尝试将数据放入数组中,然后像这样循环:
data = [
['Date','Open','High','Low','Close','Volume','Adj Close'],
['10/8/2013','1676.22','1676.79','1655.03','1655.45','3569230000','1655.45']
['10/7/2013','1687.15','1687.15','1674.7','1676.12','2678490000','1676.12'],
]
File.open('table.csv', 'w') do |f|
data.each{|line| f.puts line.join(',')}
end