Skip to content

Instantly share code, notes, and snippets.

@udzura
Created October 21, 2009 03:11
Show Gist options
  • Save udzura/214815 to your computer and use it in GitHub Desktop.
Save udzura/214815 to your computer and use it in GitHub Desktop.
require 'enumerator'
def hyphenize_numbers *args
src = args.map{|v| v.to_i}
src.sort!.uniq!
dst = [[ src[0] ]]
src.each_cons(2) do |cons|
if cons[1] - cons[0] > 1
dst << []
end
dst.last << cons[1]
end
p src
puts "--------"
p dst
dst.map! do |nums|
if nums.length == 1
nums[0].to_s
else
"#{nums.first}-#{nums.last}"
end
end
puts "--------"
puts dst.join(", ") + "."
end
if __FILE__ == $0
SRC = [1, 2, 3, 5, 6, 7, 8, 9, 12, 14]
hyphenize_numbers *SRC
=begin
#=>
[1, 2, 3, 5, 6, 7, 8, 9, 12, 14]
--------
[[1, 2, 3], [5, 6, 7, 8, 9], [12], [14]]
--------
1-3, 5-9, 12, 14.
=end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment