What Version of Ruby Am I Using?

So you go to a different machine, and you spot Ruby on it (hallelujah), and you really have nothing to so, so out of curiosity you are wondering: What version of Ruby is it?

Go ahead and execute:

ruby -v

And you should get:

ruby 1.8.5 (2006-08-25) [i486-linux]

Within an Application

But what if you want access to that information inside a Ruby application?

RUBY_VERSION # Result: "1.8.5"
RUBY_PLATFORM # Result: "i486-linux"
RUBY_RELEASE_DATE # Result: "2006-08-25"

Ruby comes with a set of constants which you can exploit to find out which version you have installed.

Testing for Version Compatibility

But what if the software only runs on certain versions of of Ruby, how do I throw an error if that criteria isn’t met?

For example Rails v1.2.3 only runs on Ruby v1.8.2 and above, except v1.8.3. In fact in v1.8.5 breakpoints are broken! (This is due to how breakpoints were initially implemented by exploiting a bug in Ruby, which got fixed in v1.8.5. Don’t worry though, in Rails 2.0 breakpoints are functional once again, without utilizing the Ruby bug.)

Well that makes for a (somewhat) complicated setup don’t you think?

The simple way is to split the RUBY_VERSION.

RUBY_VERSION.split('.') # Result: ["1", "8", "5"]

Giving you the major, minor, and tiny release numbers. Allowing you to do some version checking through conditions.

The Rails Way

Located at rails/lib/ruby_version_check.rb File

min_release  = "1.8.2 (2004-12-25)"
ruby_release = "#{RUBY_VERSION} (#{RUBY_RELEASE_DATE})"
if ruby_release =~ /1\.8\.3/
  abort <<-end_message

    Rails does not work with Ruby version 1.8.3.
    Please upgrade to version 1.8.4 or downgrade to 1.8.2.

  end_message
elsif ruby_release < min_release
  abort <<-end_message

    Rails requires Ruby version #{min_release} or later.
    You're running #{ruby_release}; please upgrade to continue.

  end_message
end
  • Line 3 does a simple regular expression check to ensure that its not running v1.8.3.
  • Line 10 just does a basic string comparison to ensure that the current version, is not less than the require minimum version.

Conclusion

Well thats enough to get you started, so get hacking!

Note: Updated to reflect hindsight on my part