MST
星途 面试题库

面试题:Ruby跨平台兼容性之系统命令调用

在Ruby中,使用`system`或`%x()`等方式调用系统命令时,不同操作系统的命令语法有差异。例如,查看当前目录下文件列表,Windows使用`dir`命令,Linux和macOS使用`ls`命令。编写一个Ruby类,该类有一个方法`execute_system_command`,此方法能根据当前运行的操作系统(可以通过`RbConfig::CONFIG['host_os']`获取部分系统信息来判断),调用正确的命令来实现查看当前目录文件列表的功能,并处理可能出现的命令执行错误,返回命令执行结果。
49.5万 热度难度
编程语言Ruby

知识考点

AI 面试

面试题答案

一键面试
require 'rbconfig'

class SystemCommandExecutor
  def execute_system_command
    os = RbConfig::CONFIG['host_os']
    command = case os
              when /mswin|mingw/
                'dir'
              else
                'ls'
              end

    begin
      result = `#{command}`
      return result
    rescue StandardError => e
      return "执行命令出错: #{e.message}"
    end
  end
end

你可以这样调用这个方法:

executor = SystemCommandExecutor.new
puts executor.execute_system_command