面试题答案
一键面试require 'json'
category_count = Hash.new(0)
File.foreach('large_log_file.log') do |line|
begin
record = JSON.parse(line)
category = record['category']
category_count[category] += 1
rescue JSON::ParserError
# 处理JSON解析错误,跳过当前行
next
end
end
category_count.each do |category, count|
puts "#{category}: #{count}"
end
上述代码中:
- 使用
File.foreach
逐行读取文件,避免一次性加载整个大文件到内存中。 - 对每行JSON字符串进行解析,若解析失败(通过
rescue JSON::ParserError
),则跳过当前行。 - 根据
category
字段统计每个分类的记录数量,并最终输出每个分类及其对应的数量。