How can I find which operating system my Ruby program is running on?

Viewed 40821

I want my Ruby program to do different things on a Mac than on Windows. How can I find out on which system my program is running?

11 Answers

Use the RUBY_PLATFORM constant, and optionally wrap it in a module to make it more friendly:

module OS
  def OS.windows?
    (/cygwin|mswin|mingw|bccwin|wince|emx/ =~ RUBY_PLATFORM) != nil
  end

  def OS.mac?
   (/darwin/ =~ RUBY_PLATFORM) != nil
  end

  def OS.unix?
    !OS.windows?
  end

  def OS.linux?
    OS.unix? and not OS.mac?
  end

  def OS.jruby?
    RUBY_ENGINE == 'jruby'
  end
end

It is not perfect, but works well for the platforms that I do development on, and it's easy enough to extend.

Either

irb(main):002:0> require 'rbconfig'
=> true
irb(main):003:0> Config::CONFIG["arch"]
=> "i686-linux"

or

irb(main):004:0> RUBY_PLATFORM
=> "i686-linux"

Try the Launchy gem (gem install launchy):

require 'launchy'
Launchy::Application.new.host_os_family # => :windows, :darwin, :nix, or :cygwin 

For something readily accessible in most Ruby installations that is already somewhat processed for you, I recommend these:

  1. Gem::Platform.local.os #=> eg. "mingw32", "java", "linux", "cygwin", "aix", "dalvik" (code)
  2. Gem.win_platform? #=> eg. true, false (code)

Both these and every other platform checking script I know is based on interpreting these underlying variables:

  1. RbConfig::CONFIG["host_os"] #=> eg. "linux-gnu" (code 1, 2)
  2. RbConfig::CONFIG["arch"] #=> eg. "i686-linux", "i386-linux-gnu" (passed as parameter when the Ruby interpreter is compiled)
  3. RUBY_PLATFORM #=> eg. "i386-linux-gnu", "darwin" - Note that this returns "java" in JRuby! (code)
    • These are all Windows variants: /cygwin|mswin|mingw|bccwin|wince|emx/
  4. RUBY_ENGINE #=> eg. "ruby", "jruby"

Libraries are available if you don't mind the dependency and want something a little more user-friendly. Specifically, OS offers methods like OS.mac? or OS.posix?. Platform can distinguish well between a variety of Unix platforms. Platform::IMPL will return, eg. :linux, :freebsd, :netbsd, :hpux. sys-uname and sysinfo are similar. utilinfo is extremely basic, and will fail on any systems beyond Windows, Mac, and Linux.

If you want more advanced libraries with specific system details, like different Linux distributions, see my answer for Detecting Linux distribution in Ruby.

Using the os gem, when loading different binaries for IMGKit

# frozen_string_literal: true
IMGKit.configure do |config|
  if OS.linux? && OS.host_cpu == "x86_64"
    config.wkhtmltoimage =
      Rails.root.join("bin", "wkhtmltoimage-linux-amd64").to_s
  elsif OS.mac? && OS.host_cpu == "x86_64"
    config.wkhtmltoimage =
      Rails.root.join("bin", "wkhtmltoimage-macos-amd64").to_s
  else
    puts OS.report
    abort "You need to add a binary for wkhtmltoimage for your OS and CPU"
  end
end
Related