Skip to content

Instantly share code, notes, and snippets.

@rklemme rklemme/rangify.rb
Created Sep 21, 2010

Embed
What would you like to do?
#!/bin/env ruby19
Num = Struct.new :pre, :val do
def succ
self.class.new pre, val.succ
end
def to_s; "#{pre}#{val}" end
def inspect; "#{self.class.name}(#{self})" end
include Comparable
def <=>(o) to_a <=> o.to_a end
end
def Num(s)
%r{\A(\D*)(\d+)\z} =~ s or raise "bad arg %p" % s
Num.new $1, $2.to_i
end
module Enumerable
def rangify(&bl)
bl ||= lambda {|x, y| x == y ? x : (x..y)}
res = []
a = b = nil
each do |x|
case
when a.nil?
a = b = x
when x == b.succ
b = x
else
res << bl[a, b]
a = b = x
end
end
res << bl[a, b] unless a.nil?
res
end
end
test_data = [
[ '1', '2', '3', '4', '6', '7', '9', 'S1', 'S2' ],
[ '1', '2', 'S3', 'S4', 'S5', 'O6' ],
]
test_data.each {|td| td.map! {|s| Num(s)} }
test_data.each do |td|
r1 = td.rangify
r2 = td.rangify {|x,y| x == y ? x.to_s : "#{x}-#{y}"}
p td, r1, r2
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.