Module: Natcmp

Defined in:
lib/natcmp.rb

Overview

Synopsis

Natural order comparison of two strings e.g. “my_prog_v1.1.0” < “my_prog_v1.2.0” < “my_prog_v1.10.0” which does not follow alphabetically

Acknowledgments

Based on Martin Pool’s “Natural Order String Comparison” originally written in C sourcefrog.net/projects/natsort/

This implementation is Copyright © 2003, 2008, 2009, 2011 by Alan Davies.

License

This software is provided ‘as-is’, without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software.

Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:

  1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.

  2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.

  3. This notice may not be removed or altered from any source distribution.

Constant Summary collapse

VERSION =
"1.4.1"

Class Method Summary collapse

Class Method Details

.natcmp(str1, str2, ignoreCase = true) ⇒ Object

‘Natural order’ comparison of two strings.

e.g. “my_prog_v1.1.0” < “my_prog_v1.2.0” < “my_prog_v1.10.0”

which does not follow alphabetically



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/natcmp.rb', line 41

def self.natcmp(str1, str2, ignoreCase=true)
	# Split the strings into digits and non-digits
	strArrays = [str1,str2].collect do |str|
		str = str.downcase if ignoreCase
		str.tr(" \t\r\n", '').split(/(\d+)/)
	end

	# Get length of smallest array
	minSize = strArrays.min_by { |arr| arr.size }.size
	
	# Loop through all the digit parts and convert to integers if neither of them begin with a zero
	1.step(minSize-1, 2) do |i|
		unless strArrays.any? { |arr| arr[i] =~ /^0/ }
			strArrays.each { |arr| arr[i] = arr[i].to_i }
		end
	end

	strArrays[0] <=> strArrays[1]
end