How to compare versions in Ruby?

How to write a piece of code to compare some versions strings and get the newest?

For example strings like: '0.1', '0.2.1', '0.44'.


Solution 1:

Gem::Version.new('0.4.1') > Gem::Version.new('0.10.1')

Solution 2:

If you need to check pessimistic version constraints, you can use Gem::Dependency like this:

Gem::Dependency.new('', '~> 1.4.5').match?('', '1.4.6beta4')

Solution 3:

class Version < Array
  def initialize s
    super(s.split('.').map { |e| e.to_i })
  end
  def < x
    (self <=> x) < 0
  end
  def > x
    (self <=> x) > 0
  end
  def == x
    (self <=> x) == 0
  end
end
p [Version.new('1.2') < Version.new('1.2.1')]
p [Version.new('1.2') < Version.new('1.10.1')]

Solution 4:

You can use the Versionomy gem (available at github):

require 'versionomy'

v1 = Versionomy.parse('0.1')
v2 = Versionomy.parse('0.2.1')
v3 = Versionomy.parse('0.44')

v1 < v2  # => true
v2 < v3  # => true

v1 > v2  # => false
v2 > v3  # => false