检测 ruby​​ 是否在 Windows 上运行的正确方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4871309/
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-15 16:06:30  来源:igfitidea点击:

What is the correct way to detect if ruby is running on Windows?

rubywindowsoperating-system

提问by John

What is the correct way to detect from within Ruby whether the interpreter is running on Windows? "Correct" includes that it works on all major flavors of Ruby, including 1.8.x, 1.9.x, JRuby, Rubinius, and IronRuby.

从 Ruby 内部检测解释器是否在 Windows 上运行的正确方法是什么?“正确”包括它适用于所有主要的 Ruby 版本,包括 1.8.x、1.9.x、JRuby、Rubinius 和 IronRuby。

The currently top ranked Google results for "ruby detect windows" are all incorrect or outdated. For example, one incorrect way to do it is:

当前排名最高的“ruby 检测窗口”的谷歌结果都是不正确的或过时的。例如,一种不正确的做法是:

RUBY_PLATFORM =~ /mswin/

This is incorrect because it fails to detect the mingw version, or JRuby on Windows.

这是不正确的,因为它无法检测到 mingw 版本或 Windows 上的 JRuby。

What's the right way?

什么是正确的方法?

采纳答案by Dylan Markow

Preferred Option (Updated based on @John's recommendations):

首选选项(根据@John 的建议更新)

require 'rbconfig'
is_windows = (RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/)

This could also work, but is less reliable (it won't work with much older versions, and the environment variable can be modified)

这也可以工作,但不太可靠(它不适用于旧版本,并且可以修改环境变量)

is_windows = (ENV['OS'] == 'Windows_NT')

(I can't easily test either on all of the rubies listed, or anything but Windows 7, but I know that both will work for 1.9.x, IronRuby, and JRuby).

(我无法在列出的所有 rubies 或 Windows 7 以外的任何系统上轻松测试,但我知道两者都适用于 1.9.x、IronRuby 和 JRuby)。

回答by x-yuri

It turns out, there's this way:

事实证明,有这种方式

Gem.win_platform?