Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the RUBY_VERSION is greater than a certain version?

Tags:

ruby

Before I split the RUBY_VERSION string on a period and convert the bits into integers and so on, is there a simpler way to check from a Ruby program if the current RUBY_VERSION is greater than X.X.X?

like image 596
dan Avatar asked Feb 11 '11 04:02

dan


2 Answers

User diedthreetimes' answer is much simpler, and the method I use... except it uses string comparison, which is not best practice for version numbers. Better to use numeric array comparison like this:

version = RUBY_VERSION.split('.').map { |x| x.to_i }
if (version <=> [1, 8, 7]) >= 1
  ...
end
like image 182
Huw Walters Avatar answered Sep 28 '22 17:09

Huw Walters


Ruby's Gem library can do version number comparisons:

require 'rubygems' # not needed with Ruby 1.9+

ver1 = Gem::Version.new('1.8.7') # => #<Gem::Version "1.8.7">
ver2 = Gem::Version.new('1.9.2') # => #<Gem::Version "1.9.2">
ver1 <=> ver2 # => -1

See http://rubydoc.info/stdlib/rubygems/1.9.2/Gem/Version for more info.

like image 38
the Tin Man Avatar answered Sep 28 '22 17:09

the Tin Man