136

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'.

1
  • I needed to compare pessimistic version constraints a while back, but I didn't want to depend on RubyGems to do it, so I wrote a simple Version class that does everything I need: shorts.jeffkreeftmeijer.com/2014/… Oct 16, 2014 at 6:13

8 Answers 8

266
Gem::Version.new('0.4.1') > Gem::Version.new('0.10.1')
6
  • 20
    The Gem::Version... syntax made me thought I would need to install a gem. But it was not required.
    – Guillaume
    Oct 17, 2012 at 17:08
  • 1
    Note: This gives an error about undefined variable 'Gem' for me on Ruby 1.x, but works as expected on Ruby 2.x. In my case I was checking RUBY_VERSION against being Ruby 1.x (not 2.x), so I just did RUBY_VERSION.split('.')[0] == "1" like John Hyland and DigitalRoss do it.
    – uliwitness
    Jun 19, 2013 at 15:10
  • 5
    Gem::Dependency.new(nil, '~> 1.4.5').match?(nil, '1.4.6beta4')
    – levinalex
    Jul 9, 2013 at 14:17
  • 9
    @uliwitness it's not Ruby 1.x vs 2.x; it's 1.8.x vs 1.9+. Ruby through 1.8.x doesn't include rubygems by default; you need a require 'rubygems' to get access to the Gem namespace. From 1.9 on, however, it's automatically included.
    – Mark Reed
    Feb 12, 2014 at 14:35
  • This worked for comparing wildcard NPM versions too. +1 Sep 7, 2014 at 4:14
43

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')
1
  • 1
    Newer versions appear to require a string for the name. An empty string works fine, i.e. Gem::Dependency.new('', '~> 1.4.5').match?('', '1.4.6beta4') Mar 13, 2014 at 19:12
22
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')]
4
  • 3
    Like some of the other answers here, it looks like you're doing string comparisons instead of numerical, which will cause problems when comparing versions like '0.10' and '0.4'. Jan 13, 2010 at 17:00
  • 7
    Upvoted for concise solution which does not require installing a gem.
    – JD.
    Sep 5, 2012 at 18:21
  • 2
    For what it's worth: vers = (1..3000000).map{|x| "0.0.#{x}"}; 'ok' puts Time.now; vers.map{|v| ComparableVersion.new(v) }.sort.first; puts Time.now # 24 seconds 2013-10-29 13:36:09 -0700 2013-10-29 13:36:33 -0700 => nil puts Time.now; vers.map{|v| Gem::Version.new(v) }.sort.first; puts Time.now # 41 seconds 2013-10-29 13:36:53 -0700 2013-10-29 13:37:34 -0700 Code blob is making it ugly, but basically, using this vs Gem::Version is about twice as faster.
    – Shai
    Oct 29, 2013 at 20:39
  • A version is not an array, though. May 7, 2017 at 8:42
15

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
3
  • 5
    I have seen that, but require me to use 2 gems to do a really simple thing. I want to use that as last choice.
    – user239895
    Jan 12, 2010 at 18:16
  • 8
    "Don't reinvent the wheel". Because it's simple doesn't mean the programmer didn't put work and thought into it. Use the gem, read the code, and learn from it - and move on to bigger and better things!
    – Trevoke
    Jan 13, 2010 at 20:32
  • Dependency management and version maintenance is a difficult problem, probably much more difficult than the task of comparing 2 versions. I totally agree that introducing 2 more dependencies should be a last resort in this case.
    – kkodev
    Feb 16, 2017 at 14:49
11

I would do

a1 = v1.split('.').map{|s|s.to_i}
a2 = v2.split('.').map{|s|s.to_i}

Then you can do

a1 <=> a2

(and probably all the other "usual" comparisons).

...and if you want a < or > test, you can do e.g.

(a1 <=> a2) < 0

or do some more function wrapping if you're so inclined.

2
  • 1
    Array.class_eval {include Comparable} will make all arrays respond to <, >, etc. Or, if you just want to do this to certain arrays: a = [1, 2]; a.extend(Comparable) Jan 12, 2010 at 19:28
  • 5
    The problem I found with this solution is that it returns that "1.2.0" is bigger than "1.2"
    – Maria S
    Mar 14, 2012 at 6:35
9

Gem::Version is the easy way to go here:

%w<0.1 0.2.1 0.44>.map {|v| Gem::Version.new v}.max.to_s
=> "0.44"
3
  • Much better than versionomy which requires a c-extension!? Jun 18, 2013 at 21:57
  • i don't think 'max' will work.. it will report 0.5 to be greater than 0.44. Which is not true when comparing semver versions.
    – Flo Woo
    May 26, 2015 at 6:09
  • 2
    this seems to have been fixed in latest Gem::Version. 0.44 is correctly reported as higher than 0.5 now.
    – Flo Woo
    Apr 6, 2016 at 4:09
5

If you want to do it by hand without using any gems, something like the following should work, though it's a little perly looking.

versions = [ '0.10', '0.2.1', '0.4' ]
versions.map{ |v| (v.split '.').collect(&:to_i) }.max.join '.'

Essentially, you turn each version string in to an array of integers and then use the array comparison operator. You could break out the component steps to get something a little easier to follow if this is going in code somebody will need to maintain.

-1

I had the same problem, I wanted a Gem-less version comparator, came up with this:

def compare_versions(versionString1,versionString2)
    v1 = versionString1.split('.').collect(&:to_i)
    v2 = versionString2.split('.').collect(&:to_i)
    #pad with zeroes so they're the same length
    while v1.length < v2.length
        v1.push(0)
    end
    while v2.length < v1.length
        v2.push(0)
    end
    for pair in v1.zip(v2)
        diff = pair[0] - pair[1]
        return diff if diff != 0
    end
    return 0
end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.