-
-
Save lmarburger/570457 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I don't mind at all. I think your use of
returning
in your new gist very clearly states what the code does.