面试题答案
一键面试begin
input_file = ARGV[0]
output_file = ARGV[1]
unless input_file && output_file
raise ArgumentError, "请提供输入文件名和输出文件名作为参数"
end
word_count = {}
File.foreach(input_file) do |line|
line.split.each do |word|
word_count[word] ||= 0
word_count[word] += 1
end
end
File.open(output_file, 'w') do |file|
word_count.each do |word, count|
file.write("#{word}: #{count}\n")
end
end
rescue ArgumentError => e
puts "参数错误: #{e.message}"
rescue Errno::ENOENT => e
puts "文件不存在错误: #{e.message}"
rescue StandardError => e
puts "发生错误: #{e.message}"
end
使用方法:将上述代码保存为一个 .rb
文件,然后在命令行运行 ruby your_script.rb input.txt output.txt
,其中 input.txt
是要读取的文本文件,output.txt
是输出结果的文件。