Fellow Stranger - 1 month ago 4
Ruby Question

# Return first and last element in sequences

I have an array that consists of concatenated sets of incremental (+1) sequences. Here's an example with three sequences:

``````sequences = [2,3,4,7,12,13,14,15]
``````

I'm trying to get first and last element of each sequence and return an array with those values. From the array above, the result should look like this:

``````[[2,4][7,7][12,15]]
``````

I've come up with this pretty naive solution that I thought would work, but it only returns the first sequence. Any idea why? And/or any suggestion of a better solution in whole?

``````new_array   = []
start_point = sequences[0]
end_point   = sequences[0]

sequences.map do |element|
if element == end_point + 1
end_point = element
elsif element == end_point
next
else
new_array << [start_point, end_point]
startpoint   = element
end_point = element
end
end
return new_array
``````

You can use `chunk_while` to find consecutive numbers: (this is also an example in the docs)

``````sequences.chunk_while { |i, j| i + 1 == j }.to_a
#=> [[2, 3, 4], [7], [12, 13, 14, 15]]
``````

And `map` along with `values_at` to extract each sub-array's first and last element:

``````sequences.chunk_while { |i, j| i + 1 == j }.map { |a| a.values_at(0, -1) }
#=> [[2, 4], [7, 7], [12, 15]]
``````

Or more verbose:

``````....map { |a| [a.first, a.last] }
``````
Source (Stackoverflow)