Ryan Rebo
Ryan Rebo

Reputation: 1318

CSV file to hash

I want to take a simple 2-column CSV file and turn it to a Hash of initials as keys, full name as values. How would you do this?

csv_text = File.read('composer_initials.csv')

csv = CSV.parse(csv_text, :headers => true)

I've tried:

csv.to_a.map {|row| ro.to_hash}
csv.map {|row| row.to_hash}

SOLUTION:

This ended up doing the job:

composers = {}

CSV.foreach("composer_initials.csv") do |row|
  composers[row[0]] = row[1]
end

Upvotes: 0

Views: 301

Answers (1)

locoboy
locoboy

Reputation: 38910

hash = {}
csv= CSV.parse(csv_text)
csv.each do |row|
  hash[row[0]] = row[1]
end

Upvotes: 2

Related Questions