Module: NaturalSort::Engine

Defined in:
lib/natural_sort/engine.rb

Overview

Internal: Singleton module which sorts elements in a natural, human-friendly alphanumeric order.

Constant Summary collapse

REGEXP =

Internal: Main Regexp used to in natural sorting

/(^|\D+)(\d+|(\D$))/
NUMERIC =

Internal: A Regexp used to detect numeric substrings

/(\d+)/

Class Method Summary collapse

Class Method Details

.comparator(a, b) ⇒ Object

Internal: Comparator function used for sorting, which can be used as a standalone.

a - the left-hand side of the comparator b - the right-hand side of the comparator

Returns 0, 1, or -1

Examples

[person1, person2, person3].sort{|a,b| NaturalSort.comparator(a.name, b.name)}


39
40
41
42
43
44
45
46
# File 'lib/natural_sort/engine.rb', line 39

def comparator(a, b)
  sa, sb = a.to_s, b.to_s
  if (sa.downcase <=> sb.downcase) == 0 then sa <=> sb
  else
    na, nb = check_regexp(sa, sb)
    na <=> nb
  end
end

.sort(object) ⇒ Object

Internal: Static method to sort.

object - any object that is enumerable or has a #to_a method.

Returns a sorted version of the object.

Examples:

NaturalSort.sort ['a1', 'a12', 'a2']  #=> ['a1', 'a2', 'a12']


22
23
24
25
26
# File 'lib/natural_sort/engine.rb', line 22

def sort(object)
  Array(object).sort do |a,b|
    self.comparator(a,b)
  end
end