I want to load a CSV file and create objects based on the data. The file has the following structure:
product code;product name;product price;units
RTF0145;Mixer;659;15
GTF4895;PC;9999;25
While loading the data I want to skip the first row with headers but I have a trouble using the {:headers => true} attribute, the method does nothing, no error is raised.
def Store.load_data(file, separator, headers = true)
begin
@items = []
CSV.open(file, "r", {:col_sep => separator}, {:headers => headers}) do |csv|
csv.each do |product|
@items << Store.new(product["product code"], product["product name"], product["price"], product["units"])
end
end
rescue
end
end
I call the method like this:
Store.load_data("products.csv", ";")
If I use it without the headers argument everything works as expected:
def Store.load_data(file, separator, headers = true)
begin
@items = []
CSV.foreach(file, { :col_sep => separator }) do |row|
@items << Store.new(row[0], row[1], row[2], row[3]) unless row[0] == "product code"
end
rescue
end
end
return_headers: falseoption?{:col_sep => separator}, {:headers => headers})?