Skip to content

Instantly share code, notes, and snippets.

@Sixeight
Created August 24, 2011 08:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sixeight/1167633 to your computer and use it in GitHub Desktop.
Save Sixeight/1167633 to your computer and use it in GitHub Desktop.
# coding: utf-8
module NaturalOrderStringComparison
COMPARE_EXPRESSION = /^(\D*)(\d*)(.*)$/.freeze
def compare(str1, str2)
str1, str2 = str1.dup, str2.dup
while (str1.length > 0) || (str2.length > 0) do
chars1, num1, str1 = str1.match(COMPARE_EXPRESSION).values_at(1, 2, 3)
chars2, num2, str2 = str2.match(COMPARE_EXPRESSION).values_at(1, 2, 3)
result = chars1 <=> chars2
return result if result != 0
if num1[0].ord != 48 || num2[0].ord != 48
num1, num2 = num1.to_i, num2.to_i
end
result = num1 <=> num2
return result if result != 0
end
return 0
end
module_function :compare
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment