module Naturally

def self.normalize(complex_number)

Returns:
  • (Array) - an array of Segments which

Parameters:
  • complex_number (String) -- the number in a hierarchical form
def self.normalize(complex_number)
  tokens = complex_number.to_s.gsub(/\_/,'').scan(/\p{Word}+/)
  tokens.map { |t| Segment.new(t) }
end

def self.sort(an_array, by:nil)

Returns:
  • (Array) - the numbers sorted naturally.

Parameters:
  • (optional) (by) -- an attribute of the array by which to sort.
  • an_array (Array) -- the list of numbers to sort.
def self.sort(an_array, by:nil)
  if by.nil?
    an_array.sort_by { |x| normalize(x) }
  else
    self.sort_by(an_array, by)
  end
end

def self.sort_by(an_array, an_attribute=nil, &block)

Returns:
  • (Array) - the objects in natural sort order.
    Parameters:
    • &block (Block) -- a block that should evaluate to the
    • an_attribute (Symbol) -- the attribute by which to sort.
    • an_array (Array) -- the list of objects to sort.
      def self.sort_by(an_array, an_attribute=nil, &block)
        return sort_by_block(an_array, &block) if block_given?
        an_array.sort_by { |obj| normalize(obj.send(an_attribute)) }
      end

      def self.sort_by_block(an_array, &block)

      Returns:
      • (Array) - the objects in natural sort order.
        Parameters:
        • &block (Block) -- a block that should evaluate to the
        • an_array (Array) -- the list of objects to sort.
          def self.sort_by_block(an_array, &block)
            an_array.sort_by { |obj| normalize(yield(obj)) }
          end