Ruby - File IOHow 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)Check Answer
Step-by-Step SolutionSolution:Step 1: Understand headers optionPassing headers: true to CSV.read treats the first row as headers and returns CSV::Table.Step 2: Convert rows to hashesMapping each row with to_h converts CSV::Row objects to hashes with header keys.Step 3: Analyze other optionsCSV.foreach does not return array; CSV.open returns file object; CSV.generate creates CSV string.Final Answer:CSV.read('file.csv', headers: true).map(&:to_h) -> Option CQuick 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 resultsConfusing CSV.generate with reading
Master "File IO" in Ruby9 interactive learning modes - each teaches the same concept differentlyLearnWhyDeepVisualTryChallengeProjectRecallTime
More Ruby Quizzes Blocks, Procs, and Lambdas - Proc vs lambda differences (arity, return) - Quiz 12easy Blocks, Procs, and Lambdas - Method objects with method() - Quiz 15hard Class Methods and Variables - Class variables (@@) and their dangers - Quiz 5medium Enumerable and Collection Processing - Reject for inverse filtering - Quiz 5medium Enumerable and Collection Processing - Reduce/inject for accumulation - Quiz 10hard File IO - Dir operations for directories - Quiz 4medium Modules and Mixins - Custom modules as mixins - Quiz 6medium Modules and Mixins - Extend for class methods - Quiz 1easy Modules and Mixins - Module declaration syntax - Quiz 7medium Modules and Mixins - Namespacing with modules - Quiz 7medium