3 # Natural order comparison of two strings
4 # e.g. "my_prog_v1.1.0" < "my_prog_v1.2.0" < "my_prog_v1.10.0"
5 # which does not follow alphabetically
7 # Based on Martin Pool's "Natural Order String Comparison" originally written in C
8 # http://sourcefrog.net/projects/natsort/
10 # This implementation is Copyright (C) 2003 by Alan Davies
11 # <cs96and_AT_yahoo_DOT_co_DOT_uk>
13 # This software is provided 'as-is', without any express or implied
14 # warranty. In no event will the authors be held liable for any damages
15 # arising from the use of this software.
17 # Permission is granted to anyone to use this software for any purpose,
18 # including commercial applications, and to alter it and redistribute it
19 # freely, subject to the following restrictions:
21 # 1. The origin of this software must not be misrepresented; you must not
22 # claim that you wrote the original software. If you use this software
23 # in a product, an acknowledgment in the product documentation would be
24 # appreciated but is not required.
25 # 2. Altered source versions must be plainly marked as such, and must not be
26 # misrepresented as being the original software.
27 # 3. This notice may not be removed or altered from any source distribution.
31 # 'Natural order' comparison of two strings
32 def String.natcmp(str1, str2, caseInsensitive=false)
33 str1, str2 = str1.dup, str2.dup
34 compareExpression = /^(\D*)(\d*)(.*)$/
41 # Remove all whitespace
45 while (str1.length > 0) or (str2.length > 0) do
46 # Extract non-digits, digits and rest of string
47 str1 =~ compareExpression
48 chars1, num1, str1 = $1.dup, $2.dup, $3.dup
50 str2 =~ compareExpression
51 chars2, num2, str2 = $1.dup, $2.dup, $3.dup
53 # Compare the non-digits
54 case (chars1 <=> chars2)
55 when 0 # Non-digits are the same, compare the digits...
56 # If either number begins with a zero, then compare alphabetically,
57 # otherwise compare numerically
58 if (num1[0] != 48) and (num2[0] != 48)
59 num1, num2 = num1.to_i, num2.to_i
63 when -1 then return -1
66 when -1 then return -1
72 # Strings are naturally equal