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).

Parameters:

  • a (#to_s)
  • b (#to_s)

Returns:

  • (Integer)

    -1, 0, or 1



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.

Parameters:

  • value (#to_s)

Returns:



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.

Parameters:

  • input (Enumerable)

    strings (or any #to_s-able values)

Returns:

  • (Array)

    a new array in natural order



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.

Parameters:

  • input (Array)

    (or anything with #sort_by!)

Returns:

  • (Array)

    input itself, sorted

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_procProc

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.

Returns:

  • (Proc)

    a two-argument comparator returning -1, 0, or 1



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

def to_proc
  method(:compare).to_proc
end