面试题答案
一键面试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