Reputation: 11639
I'm trying to convert this csv file:
cash,units,boxes,type
12,1,4,"beer"
12,5,4,"wine"
6,3,2,"sugar"
6,5,2,"oats"
to an array of just the rows and not the header. How does one do this?
I have this:
csv = CSV.read(input_path, headers: with_headers)
which gives me a csv object with 5 rows. How do I just convert the content to an array of 4 arrays, where each subarray represents a row?
Upvotes: 5
Views: 5370
Reputation: 80065
require "csv"
p csv = CSV.table("test.csv").drop(1)
Output starts with [[12, 1, 4, "beer"],
. that is: numbers where possible, not strings everywhere.
Upvotes: 5
Reputation: 1407
Simply convert the enumerator returned by CSV#each to an array, and shift it to get rid of the headers.
rows = CSV.open(input_path).each.to_a
rows.shift
rows
=> [["12", "1", "4", "beer"], ["12", "5", "4", "wine"], ["6", "3", "2", "sugar"], ["6", "5", "2", "oats"]]
If you prefer a more elegant solution and actually want to treat headers as such:
CSV.open(input_path, headers: true, return_headers: false).map(&:fields)
Please mind that in this case .each
would yield CSV::Row
objects, not arrays.
Upvotes: 7
Reputation: 1
I am not sure about this, but I would solve it in this way
CSV.read(path, {:row_sep => :auto, :col_sep => ','}).drop(1)
In your case I believe you have to indicate ',' in the attribute :col_sep
Upvotes: -2