Module: Naturally

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

Overview

A module which performs natural sorting on a variety of number formats. (See the specs for examples.)

It achieves this by capitalizing on Ruby’s behavior when comparing arrays: The module sorts arrays of segmented numbers such as

‘1.9’, ‘1.9a’, ‘1.10’

by comparing them in their array forms.

I.e., approximately [[‘1’, ‘9’], [‘1, ’9a’], [‘1’, ‘10’]]

Defined Under Namespace

Classes: Segment

Constant Summary collapse

VERSION =
'1.3.2'

Class Method Summary collapse

Class Method Details

.normalize(complex_number) ⇒ Array<Segment>

Convert the given number an array of Segments. This enables it to be sorted against other arrays by the standard #sort method.

For example: ‘1.2a.3’ becomes [Segment<‘1’>, Segment<‘2a’>, Segment<‘3’>]

Parameters:

  • complex_number (String)

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

Returns:

  • (Array<Segment>)

    an array of Segments which can be sorted naturally via a standard #sort.



39
40
41
42
# File 'lib/naturally.rb', line 39

def self.normalize(complex_number)
  tokens = complex_number.to_s.scan(/\p{Word}+/)
  tokens.map { |t| Segment.new(t) }
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.



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

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

.sort_by(an_array, an_attribute) ⇒ Array<Object>

Sort an array of objects “naturally” by a given attribute.

Parameters:

  • an_array (Array<Object>)

    the list of objects to sort.

  • an_attribute (Symbol)

    the attribute by which to sort.

Returns:

  • (Array<Object>)

    the objects in natural sort order.



24
25
26
# File 'lib/naturally.rb', line 24

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