开发者

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

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.

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_PLATFORM =~ /mswin/

This i开发者_C百科s incorrect because it fails to detect the mingw version, or JRuby on Windows.

What's the right way?


It turns out, there's this way:

Gem.win_platform?


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

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).


This works perfectly for me Also etc does not need to be installed, it comes with ruby.

require "etc"
def check_system
  return "windows" if Etc.uname[:sysname] == "Windows_NT"
  return "linux" if Etc.uname[:sysname] == "Linux"
end


(File::ALT_SEPARATOR || File::SEPARATOR) == '\\'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜