Module: Naturally

Defined in:
lib/naturally.rb,
lib/naturally/version.rb

Defined Under Namespace

Classes: NumberElement

Constant Summary collapse

VERSION =
'1.2.1'

Class Method Summary collapse

Class Method Details

.normalize(number) ⇒ Array<NumberElement>

Convert the given number into an object that can be sorted naturally. This object is an array of NumberElement instances.

Parameters:

  • number (String)

    the number in complex form such as 1.2a.3.

Returns:

  • (Array<NumberElement>)

    an array of NumberElements which is able to be sorted naturally via a normal ‘sort’.



22
23
24
# File 'lib/naturally.rb', line 22

def self.normalize(number)
  number.to_s.scan(%r/[0-9a-zA-Z]+/o).map { |i| NumberElement.new(i) }
end

.sort(an_array) ⇒ Array<String>

Perform a natural sort.

Parameters:

  • an_array (Array<String>)

    the list of numbers to sort.

Returns:

  • (Array<String>)

    the numbers sorted naturally.



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

def self.sort(an_array)
  return an_array.sort_by { |x| normalize(x) }
end

.sort_by(an_array, an_attribute) ⇒ Object



12
13
14
# File 'lib/naturally.rb', line 12

def self.sort_by(an_array, an_attribute)
  an_array.sort_by{|i| Naturally.normalize(i.send(an_attribute))}
end