0

我使用的是 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

有人可以解决这个问题,让它工作并解释我做错了什么。

谢谢

4

2 回答 2

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

这应该有效。你不需要数组。

于 2013-10-22T18:45:14.820 回答
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                                                                           
于 2013-10-22T18:26:09.030 回答