Last active
December 18, 2015 08:29
-
-
Save jdx/5754301 to your computer and use it in GitHub Desktop.
consecutive numbers?
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
def consecutive?(array) | |
array.each_with_index.all? { |a, i| a+1 == a[i+1] } | |
end | |
def to_consecutive(array) | |
if consecutive?(array) | |
"#{array.first}-#{array.last}" | |
else | |
array.to_sentence | |
end | |
end | |
to_consecutive [1,2,3] #=> 1-3 | |
to_consecutive [1,2,4] #=> 1, 2, and 4 | |
to_consecutive [1] #=> 1 | |
to_consecutive [1,3] #=> 1 and 3 | |
to_consecutive [1,2,3,5] #=> 1, 2, 3, and 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this handles empty, one and two item arrays, and more ;)