CSV library is difficult to use. At least I'm hard to use. Write it down as a memorandum. I'm glad if you can use it as a reference.
Pass a CSV :: Row instance. I'm not sure if there is any other way. I feel it's not intuitive
row1 = CSV::Row.new(["header1", "header2"], ["row1_1", "row1_2"])
table = CSV::Table.new([row1])
pp table
#<CSV::Table mode:col_or_row row_count:2>
row1 = CSV::Row.new(["header1", "header2"], ["row1_1", "row1_2"])
table = CSV::Table.new([row1])
pp table.headers
["header1", "header2"]
I thought that [0] could get the header, but I got the first row (Is it called row?) Excluding the header. Subscript? It seems that if you specify, you can get a row instead of a header.
row1 = CSV::Row.new(["header1", "header2"], ["row1_1", "row1_2"])
table = CSV::Table.new([row1])
pp table[0]
pp table[1]
pp table["header1"]
#<CSV::Row "header1":"row1_1" "header2":"row1_2">
nil
This was an intuitive behavior.
row1 = CSV::Row.new(["header1", "header2"], ["row1_1", "row1_2"])
table = CSV::Table.new([row1])
pp table["header1"]
["row1_1"]
headers = ["header1", "header2"]
row1 = CSV::Row.new(headers, ["row1_1", "row1_2"])
row2 = CSV::Row.new(headers, ["row2_1", "row2_2"])
table = CSV::Table.new([row1, row2])
CSV.open("test.csv", "w", headers: headers, write_headers: true, force_quotes: true) do |csv|
table.each { |row| csv << row }
end
$ cat test.csv
"header1","header2"
"row1_1","row1_2"
"row2_1","row2_2"
def save_csv_table(csv_table)
headers = csv_table.headers
CSV.open("test.csv", "w", { headers: headers, write_headers: true, force_quotes: true }) do |csv|
csv_table.each{ |row| csv << row }
end
end
Recommended Posts