Bird
0
0

How can you read a CSV file and convert it into an array of hashes with headers as keys using Ruby's CSV library?

hard📝 Application Q9 of 15
Ruby - File IO
How can you read a CSV file and convert it into an array of hashes with headers as keys using Ruby's CSV library?
ACSV.open('file.csv', 'r') { |csv| csv.to_h }
BCSV.foreach('file.csv') { |row| row.to_h }
CCSV.read('file.csv', headers: true).map(&:to_h)
DCSV.generate('file.csv', headers: true)
Step-by-Step Solution
Solution:
  1. Step 1: Understand headers option

    Passing headers: true to CSV.read treats the first row as headers and returns CSV::Table.
  2. Step 2: Convert rows to hashes

    Mapping each row with to_h converts CSV::Row objects to hashes with header keys.
  3. Step 3: Analyze other options

    CSV.foreach does not return array; CSV.open returns file object; CSV.generate creates CSV string.
  4. Final Answer:

    CSV.read('file.csv', headers: true).map(&:to_h) -> Option C
  5. Quick Check:

    Use headers: true and map to_h for array of hashes [OK]
Quick Trick: Use headers: true and map(&:to_h) to get hashes [OK]
Common Mistakes:
  • Using foreach without collecting results
  • Confusing CSV.generate with reading

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes