Module: Unnatural::Substitution

Defined in:
lib/unnatural/substitution.rb

Overview

Compares strings by zero-padding integer sequences such that all are the same length. Pure Ruby. Tends to be outperformed by ‘Unnatural::Scan` on longer strings. Recommended for sorting short unicode strings.

Class Method Summary collapse

Class Method Details

.compare(a, b) ⇒ Object



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

def self.compare(a, b)
  largest = a.size < b.size ? b.size : a.size
  substitute(a, largest) <=> substitute(b, largest)
end

.sort(enumerable) ⇒ Object



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

def self.sort(enumerable)
  largest = enumerable.map(&:size).max
  enumerable.sort_by { |s| substitute(s, largest) }
end

.sort_by(enumerable) ⇒ Object

Raises:

  • (ArgumentError)


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

def self.sort_by(enumerable)
  raise ArgumentError, 'Block expected but none given' unless block_given?
  largest = enumerable.map { |e| yield e }.map(&:size).max
  enumerable.sort_by { |s| substitute((yield s), largest) }
end

.substitute(string, size) ⇒ Object



22
23
24
25
26
27
# File 'lib/unnatural/substitution.rb', line 22

def self.substitute(string, size)
  format_string = "%0#{size}d"
  string.downcase.gsub(/\d+/) do |m|
    format(format_string, m.gsub(/^0+(?=[1-9])/, ''))
  end
end