在 Ruby 中检测操作系统

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11784109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:20:50  来源:igfitidea点击:

Detecting Operating Systems in Ruby

rubyoperating-systemdetectionsketchup

提问by user1546594

Is there a way to detect the operating system in ruby? I am working on developing a sketchup tool that will need to detect Mac vs. Windows.

有没有办法检测 ruby​​ 中的操作系统?我正在开发一个需要检测 Mac 与 Windows 的 Sketchup 工具。

回答by debbie

You can use the osgem:

您可以使用os宝石:

gem install os

And then

进而

require 'os'
OS.linux?   #=> true or false
OS.windows? #=> true or false
OS.java?    #=> true or false
OS.bsd?     #=> true or false
OS.mac?     #=> true or false
# and so on.

See: https://github.com/rdp/os

见:https: //github.com/rdp/os

回答by Thomas Enebo

Here is the best one I have seen recently. It is from selenium. The reason I think it is the best is it uses rbconfig host_os field which has the advantage of working on MRI and JRuby. RUBY_PLATFORM will say 'java' on JRuby regardless of host os it is running on. You will need to mildly tweak this method:

这是我最近看到的最好的一个。它来自硒。我认为它最好的原因是它使用了 rbconfig host_os 字段,它具有在 MRI 和 JRuby 上工作的优势。RUBY_PLATFORM 会在 JRuby 上显示“java”,而不管它运行在什么主机上。您需要稍微调整此方法:

  require 'rbconfig'

  def os
    @os ||= (
      host_os = RbConfig::CONFIG['host_os']
      case host_os
      when /mswin|msys|mingw|cygwin|bccwin|wince|emc/
        :windows
      when /darwin|mac os/
        :macosx
      when /linux/
        :linux
      when /solaris|bsd/
        :unix
      else
        raise Error::WebDriverError, "unknown os: #{host_os.inspect}"
      end
    )
  end

回答by InternetSeriousBusiness

You can use

您可以使用

puts RUBY_PLATFORM

puts RUBY_PLATFORM

irb(main):001:0> RUBY_PLATFORM
=> "i686-linux"

But @Pete is right.

但@Pete 是对的。

回答by Todd A. Jacobs

You can inspect the RUBY_PLATFORMconstant, but this is known to be unreliable in certain cases, such as when running JRuby. Other options include capturing the output of the uname -acommand on POSIX systems, or using a detection gem such as sys-uname.

您可以检查RUBY_PLATFORM常量,但众所周知,这在某些情况下是不可靠的,例如在运行 JRuby 时。其他选项包括uname -a在 POSIX 系统上捕获命令的输出,或使用诸如sys-uname 之类的检测 gem 。