Created
April 12, 2012 04:01
-
-
Save rockpapergoat/2364522 to your computer and use it in GitHub Desktop.
comparing version numbers is lame
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env ruby | |
| # from puppet's package util | |
| def versioncmp(version_a, version_b) | |
| vre = /[-.]|\d+|[^-.\d]+/ | |
| ax = version_a.scan(vre) | |
| bx = version_b.scan(vre) | |
| while (ax.length>0 && bx.length>0) | |
| a = ax.shift | |
| b = bx.shift | |
| if( a == b ) then next | |
| elsif (a == '-' && b == '-') then next | |
| elsif (a == '-') then return -1 | |
| elsif (b == '-') then return 1 | |
| elsif (a == '.' && b == '.') then next | |
| elsif (a == '.' ) then return -1 | |
| elsif (b == '.' ) then return 1 | |
| elsif (a =~ /^\d+$/ && b =~ /^\d+$/) then | |
| if( a =~ /^0/ or b =~ /^0/ ) then | |
| return a.to_s.upcase <=> b.to_s.upcase | |
| end | |
| return a.to_i <=> b.to_i | |
| else | |
| return a.upcase <=> b.upcase | |
| end | |
| end | |
| version_a <=> version_b; | |
| end | |
| p versioncmp("3.2.46","3.2.45") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
i was going to approach this by turning the version strings into hashes with the array indices as keys, then comparing the two hashes, key by key. then i dug this from puppet's innards. it appears to work fine, though i don't know if the hash method is any better.