Skip to content

Instantly share code, notes, and snippets.

@shajith
Forked from jacobat/ranges.rb
Last active January 13, 2018 09:26
Show Gist options
  • Save shajith/e7fae82ce1e9d7527f9b34d0fa2f7ca7 to your computer and use it in GitHub Desktop.
Save shajith/e7fae82ce1e9d7527f9b34d0fa2f7ca7 to your computer and use it in GitHub Desktop.
def ranges(io, max_step = 1)
in_range = false
first = nil
last = nil
io.each_line do |line|
id = line.to_i
if first.nil?
first = id
last = id
next
end
if in_range
if id - last > max_step
yield first, last if last - first > 1
in_range = false
end
elsif id - last <= max_step
in_range = true
first = last
end
last = id
end
if in_range
yield first, last
end
end
io = StringIO.new(<<-EOS
1
2
3
5
6
8
11
12
13
15
16
EOS
)
p ranges(io) {|x, y| puts [x,y].inspect }
p ranges(io, 2) {|x, y| puts [x,y].inspect }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment