Module: Unnatural::Split

Defined in:
lib/unnatural/split.rb

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



15
16
17
# File 'lib/unnatural/split.rb', line 15

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

.sort(enumerable) ⇒ Object



6
7
8
# File 'lib/unnatural/split.rb', line 6

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

.sort_by(enumerable) ⇒ Object

Raises:

  • (ArgumentError)


10
11
12
13
# File 'lib/unnatural/split.rb', line 10

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



19
20
21
22
23
# File 'lib/unnatural/split.rb', line 19

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