Home > Blockchain >  Outputting data of a CSV using hash
Outputting data of a CSV using hash

Time:10-17

When I have a csv file that looks like this:

make,model,color,doors,email
dodge,charger,black,4,[email protected]
ford,focus,blue,5,[email protected]
nissan,350z,black,2,[email protected]
mazda,miata,white,2,[email protected]
honda,civid,brown,4,[email protected]
corvette,stingray,red,2,[email protected]
ford,fiesta,blue,5,[email protected]
bmw,m4,black,2,[email protected]
audi,a5,blue,2,[email protected]
subaru,brz,black,2,[email protected]
lexus,rc,black,2,[email protected]

when I try to run my code I keep getting this error,

data [:model]
^^^^

I suppose this does not work like this but I was wondering if there is a way to make this work. I am just trying to let the program output all the different models. This is my code:

require "csv"

CSV.foreach("cars.csv", headers: true) do |row|
    data = puts row.to_h
end

data [:model]
puts data

I get my csv file and then turn it into a hash and make it equal to data

CodePudding user response:

Your data variable is not defined outside the loop and there is an additional space. To create a hash of hashes(lines).

One option could be to include the index using with_index and use it to fill the empty hash that you create before:

require "csv"

data = {}

CSV.foreach("cars.csv", headers: true).with_index  do |row, i|
    data[i] = row.to_h
end

pp data

Result:

{0=>
  {"make"=>"dodge",
   "model"=>"charger",
   "color"=>"black",
   "doors"=>"4",
   "email"=>"[email protected]"},
 ... ,
 ... ,
 ... ,
 10=>
  {"make"=>"lexus",
   "model"=>"rc",
   "color"=>"black",
   "doors"=>"2",
   "email"=>"[email protected]"}}

Another option for grouping data is to read the CSV file into an array, see CSV.read in the docs to be able to group the data as requested.

On the array, you can do:

data.group_by { |d| d[:model] }
  • Related