MST

星途 面试题库

面试题:Ruby文件操作与数据结构转换

有一个CSV文件,第一行是表头,后续每行是对应的数据。用Ruby将这个CSV文件读取后,转换为一个哈希数组,其中每个哈希的键是表头的字段,值是对应的数据,并且要求处理文件中可能存在的空行和格式错误。
18.6万 热度难度
编程语言Ruby

知识考点

AI 面试

面试题答案

一键面试
require 'csv'

def csv_to_hash_array(file_path)
  hash_array = []
  CSV.foreach(file_path, headers: true) do |row|
    next if row.to_s.strip.empty? # 跳过空行
    begin
      data_hash = {}
      row.each do |header, value|
        data_hash[header] = value
      end
      hash_array << data_hash
    rescue StandardError => e
      puts "格式错误: #{e.message}"
    end
  end
  hash_array
end

你可以使用以下方式调用这个方法:

file_path = 'your_file.csv'
result = csv_to_hash_array(file_path)
puts result.inspect