Skip to content

Instantly share code, notes, and snippets.

@lmarburger
Forked from pragdave/gist:570406
Created September 8, 2010 17:27
Show Gist options
  • Save lmarburger/570457 to your computer and use it in GitHub Desktop.
Save lmarburger/570457 to your computer and use it in GitHub Desktop.
# encoding: utf-8
input = [ 1, 2, 3, 4, 5, 8, 9, 11, 12, 13, 15 ]
# Need to box the value to make it mutable
State = Struct.new(:last_value)
# divide the input into runs of consecutive numbers
slices = input.slice_before(State.new(input.first)) do |value, state|
consecutive = value == state.last_value.succ
state.last_value = value
!consecutive
end
# replace runs of 3 or more with first–last
slices.map do |runs|
runs.size < 3 ? runs : "#{ runs.first }-#{ runs.last }"
end.join(', ') # => 1–5, 8, 9, 11–13, 15
@lmarburger
Copy link
Author

It worked for me without the #flatten so I opted to omit it.

@pragdave
Copy link

pragdave commented Sep 8, 2010

Ah, right, it does. Cool. If you don't mind, I'll use a variant of this in the example

@lmarburger
Copy link
Author

I don't mind at all. I think your use of returning in your new gist very clearly states what the code does.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment