Created
April 20, 2016 14:24
-
-
Save villanuv/12df066803c430aaf3cc2084ff3b5e91 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
array_of_numbers = [1, 2, 3, 4, 8, 9, 10, 12, 14, 18] | |
def rewrite_array(array) | |
answer_string = "" | |
first_of_range = nil | |
array.each_with_index do |value, index| | |
previous_value = array[index-1] | |
# outputs last of range with dash | |
if previous_value != array[index]-1 && previous_value != first_of_range | |
answer_string += "-#{previous_value}" if index > 0 | |
end | |
# outputs first of range | |
if previous_value != value-1 | |
answer_string += ", " if index > 0 | |
answer_string += "#{value}" | |
first_of_range = value | |
end | |
end | |
answer_string | |
end | |
puts rewrite_array(array_of_numbers) == "1-4, 8-10, 12, 14, 18" # => true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment