ruby picture

RCR 268: String.natcmp

Submitted by patsplat (Sun Aug 01 02:07:06 UTC 2004)

Abstract

>Natural Order String Comparison is a useful algorithm.

Problem

From >Martin Pool:

Computer string sorting algorithms generally don't order strings containing numbers in the same way that a human would do. Consider:


    
  rfc1.txt
  rfc2086.txt
  rfc822.txt

    

It would be more friendly if the program listed the files as


    
  rfc1.txt
  rfc822.txt
  rfc2086.txt

    

Filenames sort properly if people insert leading zeros, but they don't always do that.

Proposal

Incorporate >Alan Davies natcmp.rb into the String class.

Analysis

He has a free license. Is it free enough?

Implementation


    
  1. from
  2. natcmp.rb
  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
  6. # Based on Martin Pool's "Natural Order String Comparison" originally written in C
  7. # This implementation is Copyright (C) 2003 by Alan Davies
  8. <cs96and_AT_yahoo_DOT_co_DOT_uk>
  9. # This software is provided 'as-is', without any express or implied
  10. warranty. In no event will the authors be held liable for any damages
  11. arising from the use of this software.
  12. # Permission is granted to anyone to use this software for any purpose,
  13. including commercial applications, and to alter it and redistribute it
  14. freely, subject to the following restrictions:
  15. # 1. The origin of this software must not be misrepresented; you must not
  16. claim that you wrote the original software. If you use this software
  17. in a product, an acknowledgment in the product documentation would be
  18. appreciated but is not required.
  19. 2. Altered source versions must be plainly marked as such, and must not be
  20. misrepresented as being the original software.
  21. 3. This notice may not be removed or altered from any source distribution.

class String
  1. 'Natural order' comparison of two strings
def String.natcmp(str1, str2, caseInsensitive=false)
   str1, str2 = str1.dup, str2.dup
        compareExpression = /^(\D*)(\d*)(.*)$/
        if caseInsensitive
                str1.downcase!
                str2.downcase!
        end
        # Remove all whitespace
        str1.gsub!(/\s*/, '')
        str2.gsub!(/\s*/, '')
        while (str1.length > 0) or (str2.length > 0) do
                # Extract non-digits, digits and rest of string
                str1 =~ compareExpression
                chars1, num1, str1 = $1.dup, $2.dup, $3.dup
               str2 =~ compareExpression
                chars2, num2, str2 = $1.dup, $2.dup, $3.dup
               # Compare the non-digits
                case (chars1 <=> chars2)
                        when 0 # Non-digits are the same, compare the digits...
                                # If either number begins with a zero, then compare alphabetically,
                                # otherwise compare numerically
                                if (num1[0] != 48) and (num2[0] != 48)
                                        num1, num2 = num1.to_i, num2.to_i
                                end
                               case (num1 <=> num2)
                                        when -1 then return -1
                                        when 1 then return 1
                                end
                        when -1 then return -1
                        when 1 then return 1
                end # case
        end # while
        # Strings are naturally equal
        return 0
end

end # class String
ruby picture
Comments Current voting

I'd prefer not see this in the standard String. Maybe as a loadable module it would be better, even if I never felt the need for this. You may like to specify a better "why this is needed and deserves to be in the core classes" , a simple 'is useful' is quite, well, too simple. --gabriele renzi

--


I linked to Martin Pool's web page for the abstract, because I thought the original author made the best case for this algorithm. Anyways, here goes:

  • This is a useful sorting algorithm applicable to all String objects.
  • It doesn't conflict with existing methods on String.
  • Ruby's competition offers this feature.
  • The motivation for this sorting algorithm fits the Ruby philosophy. The >php manual states: 'This function implements a comparison algorithm that orders alphanumeric strings in the way a human being would, this is described as a "natural ordering".'

That's pretty much the case for why I suggest it be on the core String class. If there is a maintenance issue, then having the above ruby script in the standard library would be fine, I'll take responsibility for maintaining it (unless original author disagrees, of course).

Cheers,

-- Patrick May


This would help everyone to make nicer, less annoying Ruby programs. I'd like it better as the standard sort method in String#<=>, though.


Strongly opposed 0
Opposed 0
Neutral 0
In favor 1
Strongly advocate 3
ruby picture
If you have registered at RCRchive, you may now sign in below. If you have not registered, you may sign up for a username and password. Registering enables you to submit new RCRs, and vote and leave comments on existing RCRs.
Your username:
Your password:

ruby picture

Powered by .