MST

星途 面试题库

面试题:Ruby自动化脚本之文件处理

请用Ruby编写一个自动化脚本,实现读取一个文本文件的内容,统计文件中单词出现的次数,并将结果输出到另一个文件中。要求使用Ruby的标准库,且代码结构清晰,具备基本的错误处理。
32.7万 热度难度
编程语言Ruby

知识考点

AI 面试

面试题答案

一键面试
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 是输出结果的文件。