Skip to content

Instantly share code, notes, and snippets.

@pullmonkey
Created November 9, 2011 21:23
Show Gist options
  • Save pullmonkey/1353088 to your computer and use it in GitHub Desktop.
Save pullmonkey/1353088 to your computer and use it in GitHub Desktop.
consolidate a sequence of concurrent numbers with hyphens
# take list of 1,2,3,5,6,7,10 and turn into 1-3,5-7,10
def self.consolidate_pdsh_values(vals)
# vals is an array
# Examples:
# 005,006,007,008,009,010,011,012 => 005-0012
# 123,4,5,6,7,8,9,10,11,12,1234,1235,1236 => 4-12,123,1234-1236
sorted_vals = vals.sort{|a,b| a.to_i <=> b.to_i}
skipped_vals = sorted_vals.each_with_index.map do |x,i|
# replace with "-" if we are in the middle of a set of concurrent numbers
(i > 0 and i + 1 < sorted_vals.size and # make sure we are in bounds
sorted_vals[i-1].to_i == x.to_i - 1 and # did we increment by 1
sorted_vals[i+1].to_i == x.to_i + 1) ? "-" : x # and will we increment by 1
end
vals = skipped_vals.join(",")
vals.gsub(/(,-)+/,"-").gsub("-,","-") # get rid of the commas
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment