-
-
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 |
It worked for me without the #flatten so I opted to omit it.
Ah, right, it does. Cool. If you don't mind, I'll use a variant of this in the example
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
I think you're missing a flatten on line 19: end.flatten.join(', ')