Skip to content

Instantly share code, notes, and snippets.

@FooBarWidget
Created April 26, 2013 10:35
Show Gist options
  • Save FooBarWidget/5466364 to your computer and use it in GitHub Desktop.
Save FooBarWidget/5466364 to your computer and use it in GitHub Desktop.
files.sort! do |a, b|
version_aware_compare(a, b)
end
def version_aware_compare(a, b)
lhsegments = to_segments(a)
rhsegments = to_segments(b)
lhsize = lhsegments.size
rhsize = rhsegments.size
limit = (lhsize > rhsize ? lhsize : rhsize) - 1
0.upto(limit) do |i|
lhs, rhs = lhsegments[i] || 0, rhsegments[i] || 0
return -1 if String === lhs && Numeric === rhs
return 1 if Numeric === lhs && String === rhs
return lhs <=> rhs if lhs != rhs
end
return 0
end
def to_segments(filename)
filename.scan(/\d+|\D+/).map do |s|
s =~ /^\d+$/ ? s.to_i : s
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment