38

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 is incorrect because it fails to detect the mingw version, or JRuby on Windows.

What's the right way?

Timur Shtatland
  • 7,599
  • 2
  • 20
  • 30
John
  • 27,017
  • 10
  • 70
  • 76
  • 8
    For completeness sake: another **wrong** way that I see often is `RUBY_PLATFORM =~ /win/`, which also misses the MinGW port (which is the one that everybody actually uses these days) and even worse, also matches Darwin, i.e. OSX. – Jörg W Mittag Feb 02 '11 at 12:05

3 Answers3

69

It turns out, there's this way:

Gem.win_platform?
abhishek77in
  • 1,530
  • 14
  • 36
x-yuri
  • 11,554
  • 9
  • 75
  • 122
  • This is from RubyGems, which is included in MRI >= 1.9. Other rubys need to include the gem in order to use this. It's excellent to know about, but doesn't quite fulfill the OP's criteria. – aenw Jul 12 '15 at 02:22
  • 3
    And these are the platforms it matches: https://github.com/rubygems/rubygems/blob/ac20ec2c0972569c76c7d344b0029016fcf5892f/lib/rubygems.rb#L122. – sschuberth Mar 01 '17 at 11:28
  • 3
    This should be the answer. – JaeGeeTee Oct 27 '17 at 14:54
  • I agree with JaeGeeTee - this is so much more elegant than the regex variant, even though they work as well. People can keep on using the same code, rather than everyone having to rely on these custom, ad-hoc regexes. I would reason that Gem.win_platform? will be more maintainable in the long run, whereas the regex may not necessarily always be true, depending on any internal changes, different operating systems or styles, and so forth. – shevy May 02 '21 at 03:21
36

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

Dylan Markow
  • 117,383
  • 23
  • 273
  • 197
0
(File::ALT_SEPARATOR || File::SEPARATOR) == '\\'
Krapo
  • 1