Created
July 10, 2013 13:06
-
-
Save davidkelley/5966131 to your computer and use it in GitHub Desktop.
Modifies the Array class in Ruby to support sorting by valid version numbers
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
#Modify Array prototype | |
class Array | |
#Sorts numerically descending, period | |
#separated occurences ie. file.10.1.2.3.git | |
def sort_by_version_number! | |
regex = /(([0-9]+\.?){4,})\./ | |
self.sort! do |a,b| | |
#Get version numbers | |
a = Gem::Version.new(a.match(regex)[1]) | |
b = Gem::Version.new(b.match(regex)[1]) | |
#Return comparison result | |
a > b ? -1 : 1 | |
end | |
self | |
end | |
#Get the latest version | |
def latest_version | |
self.sort_by_version_number! | |
self.first | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment