書き込み
- headerのセット
- パスのセット
require 'csv'
peoples = [
['alice', 14, 'femal'],
['alice', 15, 'femal'],
['alice', 16, 'femal'],
]
headers = ["名前", "年齢", "性別"]
file_path = "./test.csv"
CSV.open(file_path, 'w', headers: headers ) do |row|
row << headers
peoples.each do |pe|
row << pe
end
end
読み込み
- headers trueを適応
- 要素を出力する
require 'csv'
file_path = "./test.csv"
CSV.foreach(file_path, headers: true) do |row|
p row
end
CSV.foreach(file_path, headers: true) do |row|
p row["名前"]
p row["年齢"]
p row["性別"]
end