使其基於您的起始代碼,我會做一些事情,如:
def export_data
File.open('coffee_orders.csv', 'a') do |csv|
csv << [Time.now, @item_name, @amount].join(', ')
end
end
或者:
def export_data
File.open('coffee_orders.csv', 'a') do |csv|
csv << '%s, %s, %s' % [Time.now, @item_name, @amount].map(&:to_s)
end
end
注意,這是沒有必要使用'a+'
追加到文件。除非您在打開文件時絕對需要「讀取」模式,否則請僅使用'a'
。這裏的IO.new文件說什麼:
"a" Write-only, starts at end of file if file exists,
otherwise creates a new file for writing.
"a+" Read-write, starts at end of file if file exists,
otherwise creates a new file for reading and
writing.
我會寫我自己會的方式是這樣的:
CSV_FILENAME = 'coffee_orders.csv'
def export_data
csv_has_content = File.size?(CSV_FILENAME)
CSV.open(CSV_FILENAME, 'a') do |csv|
csv << %w[Time Item Amount] unless csv_has_content
csv << [Time.now, @item_name, @amount]
end
end
這將使用Ruby的CSV類來處理所有的插件和奏。它檢查文件是否已經存在,如果沒有內容,它會在寫入內容之前寫入文件頭。
不要嘗試創建自己的CSV生成器。相反,使用Ruby的內置[CSV](http://ruby-doc.org/stdlib-2.0/libdoc/csv/rdoc/CSV.html)類。 CSV是一種非常糟糕的格式,在嘗試重新加載數據並被咬住之前,可能會有一些難以識別的細節。你目前的使用很簡單,但它不會總是這樣,而且養成正確的做法會對你有所幫助。 –