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.)
Defined Under Namespace
Classes: Segment
Constant Summary collapse
- VERSION =
Gem version
'2.2.1'
Class Method Summary collapse
-
.normalize(complex_number) ⇒ Array<Segment>
Convert the given number to an array of Segments.
-
.sort(an_array, by: nil) ⇒ Array<String>
Perform a natural sort.
-
.sort_by(an_array, an_attribute = nil, &block) ⇒ Array<Object>
Sort an array of objects “naturally” by a given attribute.
Class Method Details
.normalize(complex_number) ⇒ Array<Segment>
Convert the given number to an array of Segments. This enables it to be sorted against other arrays by the built-in #sort method.
For example, ‘1.2a.3’ becomes
- Segment<‘1’>, Segment<‘2a’>, Segment<‘3’>
47 48 49 50 |
# File 'lib/naturally.rb', line 47 def self.normalize(complex_number) tokens = complex_number.to_s.gsub(/\_/,'').scan(/\p{Word}+/) tokens.map { |t| Segment.new(t) } end |
.sort(an_array, by: nil) ⇒ Array<String>
Perform a natural sort. Supports two syntaxes:
-
sort(objects) # Simple arrays
-
sort(objects, by: some_attribute) # Complex objects
14 15 16 17 18 19 20 |
# File 'lib/naturally.rb', line 14 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 |
.sort_by(an_array, an_attribute = nil, &block) ⇒ Array<Object>
Sort an array of objects “naturally” by a given attribute. If block is given, attribute is ignored and each object is yielded to the block to obtain the sort key.
31 32 33 34 |
# File 'lib/naturally.rb', line 31 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 |