从Ruby中检测解释器是否在Windows上运行的正确方法是什么?"正确"包括它适用于所有主要版本的Ruby,包括1.8.x,1.9.x,JRuby,Rubinius和IronRuby.
目前排名靠前的"红宝石检测窗口"的Google搜索结果都是错误的或过时的.例如,一种不正确的方法是:
RUBY_PLATFORM =~ /mswin/
Run Code Online (Sandbox Code Playgroud)
这是不正确的,因为它无法在Windows上检测到mingw版本或JRuby.
什么是正确的方法?
x-y*_*uri 62
事实证明,就是这样:
Gem.win_platform?
Run Code Online (Sandbox Code Playgroud)
Dyl*_*kow 33
首选项(根据@ John的推荐更新):
require 'rbconfig'
is_windows = (RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/)
Run Code Online (Sandbox Code Playgroud)
这也可以工作,但不太可靠(它不适用于旧版本,并且可以修改环境变量)
is_windows = (ENV['OS'] == 'Windows_NT')
Run Code Online (Sandbox Code Playgroud)
(我不能轻易地测试列出的所有红宝石,或者除了Windows 7之外的任何东西,但我知道它们都适用于1.9.x,IronRuby和JRuby).