Class: Nodesets::HumanSortableArray

Inherits:
Array
  • Object
show all
Defined in:
lib/nodesets/human_sortable_array.rb

Overview

www.zenspider.com/ruby/2012/01/array-natural_sort.html dzone.com/articles/convert-ruby-array-ranges This has been improved since the posting a.to_ranges.map { |x| x.count > 1 ? x.to_s.gsub!(/([]+)[.]2]+([[:digit:]]+)/,‘‘) : x.first }

Instance Method Summary collapse

Instance Method Details

#human_sortObject

def initialize(arr, compact_uniq = false, sorted = false)

@compact_uniq = compact_uniq
@sorted       = sorted
super(arr)

end



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

def human_sort
  self.sort_by { |item| item.to_s.split(/(\d+)/).map { |e| [e.to_i, e] } }
end

#to_rangesObject



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/nodesets/human_sortable_array.rb', line 15

def to_ranges
  array = self
  #array = HumanSortableArray.new(self).human_sort
  #array = if not @compact_uniq && @sorted
  #  HumanSortableArray.new(self.compact.uniq, true, true).human_sort_simple
  #else
  #  self
  #end
  #array = HumanSortableArray.new(self.compact.uniq, true, true).human_sort
  ranges = []
  if !array.empty?
    # Initialize the left and right endpoints of the range
    left, right = array.first, nil
    array.each do |obj|
      # If the right endpoint is set and obj is not equal to right's successor
      # then we need to create a range.
      if right && obj != right.succ
        ranges << (left == right ? left : Range.new(left,right))
        left = obj
      end
      right = obj
    end
    ranges << (left == right ? left : Range.new(left,right))
  end
  ranges
end