[ create a new paste ] login | about

Link: http://codepad.org/Enttbyo7    [ raw code | output | fork ]

Ruby, pasted on Apr 17:
1
2
3
4
5
6
7
8
str = "2 8 5 4 6 2 5" # => "2, 4-6, 8."

p str.split(/\s+/).map{|e| e.to_i}.sort.inject([[]]){|b, e|
  if [nil, e, e-1].index(b.last.last) then b.last << e else b << [e] end
  b
}.map{|e|
  "#{e.first}" + if e.first == e.last then "" else "-#{e.last}" end
}.join(", ") + "."


Output:
1
"2, 4-6, 8."


Create a new paste based on this one


Comments: