Created
October 3, 2013 04:30
-
-
Save ahimmelstoss/6804999 to your computer and use it in GitHub Desktop.
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
class Array | |
def version_sort | |
return self.sort {|a,b| my_comparison(a, b) } | |
end | |
#split each string by - or . and then sort by those parts | |
def my_comparison(left, right) #returns -1 or 0 or 1 | |
left_array = left.split(/[-\.]/) #left array | |
right_array = right.split(/[-\.]/) #right array | |
left_array.pop | |
right_array.pop | |
while left_array.size < 4 | |
left_array.push("0") | |
end | |
while right_array.size < 4 | |
right_array.push("0") | |
end | |
puts "left_array = #{left_array}" | |
puts "right_array = #{right_array}" | |
if left_array[0] == right_array[0] | |
if left_array[1] == right_array[1] | |
if left_array[2] == right_array[2] | |
if left_array[3] == right_array[3] | |
return 0 | |
else | |
return left_array[3].to_i <=> right_array[3].to_i | |
end | |
else | |
return left_array[2].to_i <=> right_array[2].to_i | |
end | |
else | |
return left_array[1].to_i <=> right_array[1].to_i | |
end | |
else | |
return left_array[0].to_i <=> right_array[0].to_i | |
end | |
end | |
end | |
filenames = [ | |
"foo-1.10.2.ext", | |
"foo-1.11.ext", | |
"foo-1.3.ext", | |
"foo-1.50.ext", | |
"foo-1.8.7.ext", | |
"foo-1.9.3.ext", | |
"foo-1.ext", | |
"foo-10.1.ext", | |
"foo-10.ext", | |
"foo-100.ext", | |
"foo-2.0.0.ext", | |
"foo-2.0.1.ext", | |
"foo-2.0.ext", | |
"foo-2.007.ext", | |
"foo-2.01.ext", | |
"foo-2.012b.ext", | |
"foo-2.01a.ext", | |
"foo-2.0a.ext", | |
"foo-13.ext", | |
"foo-2.0b.ext", | |
"foo-2.1.ext", | |
"foo-25.ext", | |
"foo-6.ext", | |
] | |
puts filenames.version_sort |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment