50

Is there a way to detect the operating system in ruby? I am working on developing a sketchup tool that will need to detect Mac vs. Windows.

brian d foy
  • 129,424
  • 31
  • 207
  • 592
user1546594
  • 539
  • 1
  • 4
  • 4
  • 4
    Can you give us more details around *why* you need to do this? Often feature detection can be more helpful than blanket OS detection. – Pete Aug 02 '12 at 19:05

4 Answers4

76

You can use the os gem:

gem install os

And then

require 'os'
OS.linux?   #=> true or false
OS.windows? #=> true or false
OS.java?    #=> true or false
OS.bsd?     #=> true or false
OS.mac?     #=> true or false
# and so on.

See: https://github.com/rdp/os

manroe
  • 1,645
  • 20
  • 35
debbie
  • 969
  • 9
  • 14
  • 2
    Thanks for finding that. Awesome answer. :) Sadly, you have two years of votes to catch up on. – Gerry Jan 22 '15 at 22:41
60

Here is the best one I have seen recently. It is from selenium. The reason I think it is the best is it uses rbconfig host_os field which has the advantage of working on MRI and JRuby. RUBY_PLATFORM will say 'java' on JRuby regardless of host os it is running on. You will need to mildly tweak this method:

  require 'rbconfig'

  def os
    @os ||= (
      host_os = RbConfig::CONFIG['host_os']
      case host_os
      when /mswin|msys|mingw|cygwin|bccwin|wince|emc/
        :windows
      when /darwin|mac os/
        :macosx
      when /linux/
        :linux
      when /solaris|bsd/
        :unix
      else
        raise Error::WebDriverError, "unknown os: #{host_os.inspect}"
      end
    )
  end
Thomas Enebo
  • 822
  • 6
  • 3
  • Nice, but I think you should update your answer to make note of the "os" gem, which already addresses the JRuby problem you mentioned and gets this detection code of our your code base. See: http://stackoverflow.com/a/20579735/109561 – Gerry Jan 22 '15 at 22:45
  • This is also a great method if you cant install a gem to a system. Like in the case I am currently working on, where I am building a low level system script that doesn't have access to install anything at the point where I need to know the os version. <3 – utx0_ Oct 19 '17 at 08:07
29

You can use

puts RUBY_PLATFORM

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

But @Pete is right.

4

You can inspect the RUBY_PLATFORM constant, but this is known to be unreliable in certain cases, such as when running JRuby. Other options include capturing the output of the uname -a command on POSIX systems, or using a detection gem such as sys-uname.

Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199