Featured image

When developing Ruby libraries or scripts, one important task is determining which operating system your code is running on. This can be achieved in various ways — for instance, by using built-in constants or the os gem. You also shouldn’t forget that you can manually run an OS info command (uname) and check its output (naturally, making sure to ignore any errors if the command doesn’t exist on the current OS).

RUBY_PLATFORM.split('-',2)[1]
=> "linux"

Ruby::PLATFORM.split('-',2)[1] # ruby >= 4.0.0
=> "linux"

require 'rbconfig'
RbConfig::CONFIG['host_os']
=> "linux"

Gem.target_rbconfig['arch'].split('-',2)[1]
=> "linux"

Gem::Platform.local.os
=> "linux"

require 'etc'
Etc.uname[:sysname]
=> "Linux"
# gem install os
require 'os'

OS.linux?
=> true
def linux?
  !!(`uname -a` =~ /linux/i) # or cat /proc/version
rescue Errno::ENOENT
  false
end

linux?
=> true

More examples of use cases can be seen here and here.

Which of these methods have you used in your own code? Or perhaps you know of other ways to detect the OS in Ruby?