Home > Software engineering >  How to make a CSV file into a hash
How to make a CSV file into a hash

Time:10-11

In ruby, if I have a CSV file that looks like this:

make,model,color,doors
dodge,charger,black,4
ford,focus,blue,5
nissan,350z,black,2
mazda,miata,white,2
honda,civid,brown,4
corvette,stingray,red,2
ford,fiesta,blue,5

How would I be able to turn this CSV data into a hash and be able to manipulate it as a regular hash. I tried looking for an answer in StackOverflow but could not seem to find one. I tried to find other example online as well but they did not exactly work.

CodePudding user response:

You need to just try

require 'csv'

CSV.open(filename, headers: :first_row).map(&:to_h)

Also you can get reference form below link

Convert CSV file into array of hashes

  • Related