DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Detect If Your Running On Windows

  • submit to reddit
        It's an unfortunate necessity that you need to write different code for windows sometimes or at the very least load different libraries since there is no fork(), etc. This is how you can tell.

# Returns true if we are running on a MS windows platform, false otherwise.

def Kernel.is_windows?
  processor, platform, *rest = RUBY_PLATFORM.split("-")
  platform == 'mswin32'


Michael Slattery replied on Wed, 2014/02/05 - 6:24pm

Here's how Puppet  does it:

require 'rbconfig'

is_win = RbConfig::CONFIG['host_os'] =~ /mswin|win32|dos|mingw|cygwin/i

Snippets Manager replied on Sun, 2010/11/28 - 1:26pm

I'd recommend that there be three tests, rather than include mingw32 and cygwin32. There are major OS differences between mingw32, cygwin32 and Windows, that could cause problems with paths, assumption of commands and features of the OS, etc. def Kernel.is_windows? !!RUBY_PLATFORM['mswin32'] end def Kernel.is_windows_ming? !!RUBY_PLATFORM['mingw'] end def Kernel.is_windows_cygwin? !!RUBY_PLATFORM['cygwin'] end More specific tests could look for 32-bit mode in the platforms, thought the bit-ness of the architecture shouldn't make as much of a difference as the OS being sensed.

Snippets Manager replied on Fri, 2010/10/01 - 6:57am

In windows vista or windows 7 you should ask for minigw32. def Kernel.is_windows? processor, platform, *rest = RUBY_PLATFORM.split("-") platform == 'mingw32' end if Kernel.is_windows? == true puts "Windows" else puts "Unknown" end

Snippets Manager replied on Mon, 2012/05/07 - 2:24pm

Really, the test should be something like RUBY_PLATFORM =~ /(win|w)32$/ because you might also have mingw32 and cygwin32

Snippets Manager replied on Mon, 2006/01/23 - 6:05am

Why not just use a regex like RUBY_PLATFORM =~ /mswin32/ instead of adding the overhead of the split?