Created
September 8, 2012 11:51
-
-
Save kevinkirkup/3674134 to your computer and use it in GitHub Desktop.
Rubyx - Array natural number sorting
This file contains 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
################################################## | |
# Add natural number sorting to arrays | |
################################################## | |
class Array | |
# Method which sort an array composed of strings with embedded numbers by | |
# the 'natural' representation of numbers inside a string. | |
def natcmp | |
reg_number = /\d+/ | |
# We call the sort method of the Array class. | |
self.sort do |str1, str2| | |
# We try to find an embedded number | |
a = str1.match(reg_number) | |
b = str2.match(reg_number) | |
# If there is no number | |
if [a,b].include? nil | |
str1 <=> str2 | |
else | |
while true | |
begin | |
# We compare strings before the number. If there | |
# are equal, we will have to compare the numbers | |
if (comp = a.pre_match <=> b.pre_match) == 0 | |
# If the numbers are equal | |
comp = (a[0] == b[0]) ? comp = a[0] + a.post_match <=> b[0] + b.post_match : | |
comp = a[0].to_i <=> b[0].to_i | |
end | |
str1, str2 = a.post_match, b.post_match | |
a = str1.match(reg_number) | |
b = str2.match(reg_number) | |
rescue | |
break | |
end | |
end | |
comp | |
end | |
end | |
end | |
# Same as 'natcmp' but replace in place. | |
def natcmp! | |
self.replace(natcmp) | |
end | |
end | |
... | |
# Sort the array, inplace using natural number sorting | |
files.natcmp! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment