MST

星途 面试题库

面试题:Ruby命令行工具的复杂交互设计

开发一个Ruby命令行工具,实现类似 `grep` 的功能。该工具接收一个字符串和多个文件路径作为参数,在指定文件中查找包含该字符串的行并输出。此外,工具需支持 `-i` 选项,该选项表示在找到匹配行的文件中直接替换匹配的字符串(替换内容也作为参数传入)。请合理设计命令行选项解析和文件操作逻辑。
38.3万 热度难度
编程语言Ruby

知识考点

AI 面试

面试题答案

一键面试
require 'optparse'

options = {
  replace: false,
  replace_with: ''
}

OptionParser.new do |opts|
  opts.banner = "Usage: grep_like.rb [options] search_string file1 file2 ..."

  opts.on('-i', '--replace REPLACE_WITH', 'Replace the matched string in the file') do |replace_with|
    options[:replace] = true
    options[:replace_with] = replace_with
  end
end.parse!

search_string = ARGV.first
file_paths = ARGV[1..-1]

file_paths.each do |file_path|
  if File.file?(file_path)
    lines = File.readlines(file_path)
    new_lines = []
    lines.each do |line|
      if line.include?(search_string)
        if options[:replace]
          new_lines << line.gsub(search_string, options[:replace_with])
        else
          puts line.chomp
        end
      else
        new_lines << line
      end
    end
    if options[:replace]
      File.write(file_path, new_lines.join)
    end
  else
    puts "Warning: #{file_path} is not a valid file."
  end
end