In ruby if I have a CSV file called, vehicles.csv:
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
This is my code:
require "csv"
file = CSV.open("vehicles.csv", headers: :first_row).map(&:to_h)
puts file["make"]
I turn this csv file into a hash and then try to output one of the keys of the hash but keep getting "no implicit conversion of String into Integer" what must be done? I am trying to get something that looks like this as the output:
dodge
ford
nissan
mazda
honda
corvette
ford
CodePudding user response:
file = CSV.open("vehicles.csv", headers: :first_row).map(&:to_h)
leaves file as an array of hashes. Try this to see what I mean.
require "csv"
file = CSV.open("vehicles.csv", headers: :first_row).map(&:to_h)
puts file.class
puts file.first.class
puts file.first
puts file.map {_1["make"]}
Another way to accomplish what you want is read the csv file into a table and then use the values_at method to get all the data in a given column
file = CSV.open("vehicles.csv", headers: :first_row)
table = file.read
puts table.values_at("make")