面试题答案
一键面试require 'csv'
def extract_ages(file_path)
begin
ages = []
CSV.foreach(file_path, headers: true) do |row|
age = row['年龄']&.to_i
ages << age if age
end
ages
rescue Errno::ENOENT
[]
rescue CSV::MalformedCSVError
[]
end
end
你可以使用以下方式调用这个方法:
file_path = 'your_file.csv'
ages_array = extract_ages(file_path)
puts ages_array.inspect