Module: Unnatural::Split

Defined in:
lib/unnatural/split.rb

Overview

Compares strings by spliting them into arrays of alternating string and integer values. Pure Ruby. Tends to be outperformed by the others.

Constant Summary collapse

SPLITTER =
/(?<=\d)(?=\D)|(?<=\D)(?=\d)/
PRED =
['0'.ord.pred.chr].freeze

Class Method Summary collapse

Class Method Details

.compare(a, b) ⇒ Object



17
18
19
# File 'lib/unnatural/split.rb', line 17

def self.compare(a, b)
  split(a) <=> split(b)
end

.sort(enumerable) ⇒ Object



8
9
10
# File 'lib/unnatural/split.rb', line 8

def self.sort(enumerable)
  enumerable.sort_by { |s| split(s) }
end

.sort_by(enumerable) ⇒ Object

Raises:

  • (ArgumentError)


12
13
14
15
# File 'lib/unnatural/split.rb', line 12

def self.sort_by(enumerable)
  raise ArgumentError, 'Block expected but none given' unless block_given?
  enumerable.sort_by { |s| split(yield s) }
end

.split(string) ⇒ Object



21
22
23
24
25
# File 'lib/unnatural/split.rb', line 21

def self.split(string)
  array = string.downcase.split(SPLITTER)
  array = PRED + array if ('0'..'9').cover?(array[0])
  array.map.with_index { |e, i| i.odd? ? e.to_i : e }
end