Detecting Operating Systems in Ruby

RubyOperating SystemDetectionSketchup

Ruby Problem Overview


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.

Ruby Solutions


Solution 1 - Ruby

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

Solution 2 - Ruby

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

Solution 3 - Ruby

You can use

puts RUBY_PLATFORM

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

But @Pete is right.

Solution 4 - Ruby

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1546594View Question on Stackoverflow
Solution 1 - RubydebbieView Answer on Stackoverflow
Solution 2 - RubyThomas EneboView Answer on Stackoverflow
Solution 3 - RubyInternetSeriousBusinessView Answer on Stackoverflow
Solution 4 - RubyTodd A. JacobsView Answer on Stackoverflow