Class: Array

Inherits:
Object
  • Object
show all
Defined in:
lib/zipcoder/ext/array.rb

Instance Method Summary collapse

Instance Method Details

#combine_zipsObject



4
5
6
7
8
9
10
11
12
13
14
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
41
42
43
# File 'lib/zipcoder/ext/array.rb', line 4

def combine_zips
  zips = []
  start = nil
  last = nil

  self.sort.each do |zip|
    zip_int = zip.to_i

    if start == nil
      start = zip_int
      last = zip_int
    else
      if zip_int == last+1
        last = zip_int
      else
        if last == start
          zips << start.to_zip
        else
          zips << "#{start.to_zip}-#{last.to_zip}"
        end
        start = zip_int
        last = zip_int
      end
    end

  end

  # Return nil if the array is empty
  if last == nil and start == nil
      return ''
  end

  if last == start
    zips << start.to_zip
  else
    zips << "#{start.to_zip}-#{last.to_zip}"
  end

  zips.join ","
end