Method: RIEL::StringExt#to_ranges

Defined in:
lib/riel/string.rb

#to_ranges(args = Hash.new) ⇒ Object

Splits num into array of ranges, limiting itself to args[:min] and args[:max], if specified. The args[:collapse], if true, results in sequential values put into the same range.

Examples:

"1,2".to_ranges                                   # [ 1 .. 1, 2 .. 2 ]
"1,2".to_ranges :collapse => true                 # [ 1 .. 2 ]
"1-4".to_ranges                                   # [ 1 .. 4 ]
"1-3,5-6,10,11,12,".to_ranges :collapse => true   # [ 1 .. 3, 5 .. 6, 10 .. 12 ]
"1-3,5-6,10,11,12,".to_ranges                     # [ 1 .. 3, 5 .. 6, 10 .. 10, 11 .. 11, 12 .. 12 ]
"-4".to_ranges                                    # [ -String::Infinity ..  4 ]
"4-".to_ranges                                    # [ 4 .. String::Infinity ]
"1-".to_ranges :min => 0, :max => 8               # [ 1 .. 8 ]


67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/riel/string.rb', line 67

def to_ranges args = Hash.new
  min = args[:min] || -Infinity
  max = args[:max] || Infinity
  collapse = args[:collapse]
  
  ranges = Array.new
  self.split(%r{\s*,\s*}).each do |section|
    md = section.match(RANGE_REGEXP)
    next unless md
    
    from = _matchdata_to_number md, 1, min
    to = _has_matchdata?(md, 2) ? _matchdata_to_number(md, 3, max) : from

    prevrange = ranges[-1]

    if collapse && prevrange && prevrange.include?(from - 1) && prevrange.include?(to - 1)
      ranges[-1] = (prevrange.first .. to)
    else
      ranges << (from .. to)
    end
  end

  ranges
end