Module: NaturalSort

Defined in:
lib/natural_sort.rb,
lib/natural_sort/key.rb,
lib/natural_sort/version.rb,
lib/natural_sort/refinements.rb

Defined Under Namespace

Classes: Key

Constant Summary collapse

VERSION =
"1.0.0"

Class Method Summary collapse

Class Method Details

.compare(a, b) ⇒ Integer

Three-way natural-order comparison of two values (each coerced via #to_s).



47
48
49
# File 'lib/natural_sort.rb', line 47

def compare(a, b)
  Key.new(a) <=> Key.new(b)
end

.key(value) ⇒ NaturalSort::Key

The comparable sort key for value, for use as a sort_by key.



55
56
57
# File 'lib/natural_sort.rb', line 55

def key(value)
  Key.new(value)
end

.sort(input) ⇒ Array

Natural-sorts input into a new array. Not stable: elements whose natural-order keys are equal may be reordered relative to each other.



25
26
27
# File 'lib/natural_sort.rb', line 25

def sort(input)
  input.sort_by { |element| Key.new(element) }
end

.sort!(input) ⇒ Array

Natural-sorts input in place. Like sort, not stable for equal keys.

Raises:

  • (ArgumentError) —

    when input cannot be sorted in place



34
35
36
37
38
39
40
# File 'lib/natural_sort.rb', line 34

def sort!(input)
  unless input.respond_to?(:sort_by!)
    raise ArgumentError, "sort! needs an Array (or anything with #sort_by!); use sort for other enumerables"
  end

  input.sort_by! { |element| Key.new(element) }
end

.to_proc ⇒ Proc

Comparator proc, so the module itself works as a sort block: list.sort(&NaturalSort). Prefer sort or sort_by { NaturalSort.key(x) } when speed matters — those build one key per element instead of one per comparison.



16
17
18
# File 'lib/natural_sort.rb', line 16

def to_proc
  method(:compare).to_proc
end