Proper way to detect Windows platform in Ruby

I’ve seen this time and again, the Windows platform detection in Ruby is typically done like this: RUBY_PLATFORM =~ /mswin/. THIS IS WRONG! First, there is also mingw version of Ruby on Windows. So, folks started to use the updated check pattern: RUBY_PLATFORM =~ /mswin|mingw/. THIS IS WRONG TOO! There are other implementations of Ruby, like JRuby and IronRuby. And in JRuby the RUBY_PLATFORM value is “java”, it is platform-independent value, expressing one of the core JRuby properties – it is built on top of Java platform. Plus, every time new implementation comes along, all old checks would be obsolete once again.

Now, the proper way to check the Windows platform, which is surprisingly less-known. Use rbconfig!

require ‘rbconfig’

WINDOZE = Config::CONFIG[‘host_os’] =~ /mswin|mingw/

This will work for x32 and x64 versions of Ruby, for mingw-based Ruby, for IronRuby, and for reasonably fresh JRuby (1.3.1, 1.4, 1.5+) as well. Please, please, update your sources!

4 Responses to “Proper way to detect Windows platform in Ruby”

  1. Robert Says:

    Ah nice one. I’m no Ruby expert, but use it for builds and acceptance testing (cucumber/watir) in our .Net environment.

    We’re switching architecture at the moment, so it’s something I need to know for the build. Was close to doing it the way you mention not to.

    Great tip.

  2. roger Says:

    Here’s how I currently do it
    $ gem install sane

    then

    require ‘sane/os’ # ok so it’s my own gem
    OS.windows?

    :)

  3. Ennuyer.net » Blog Archive » Rails Reading - November 15, 2009 Says:

    [...] Proper way to detect Windows platform in Ruby – The Empty Way [...]

  4. Andrew Grimm Says:

    Do you happen to know how to detect if you can call fork (which’d be false by default on jruby, even on OSs that support it)?

Leave a Reply