module Naturally
def self.normalize(complex_number)
-
(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)
-
(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)
-
(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)
-
(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
def self.sort_filenames(array)
Dots are given higher priority by inserting a '0' segment, as in user workaround.
Natural sort for filenames, treating underscores and dots as separators.
def self.sort_filenames(array) array.sort_by do |filename| # Replace '.' with '.0.' to give dot higher priority, then split on dot or underscore filename.to_s.gsub('.', '.0.').split(/[\._]/).map { |t| Segment.new(t) } end end