I have an array and I'd like to select only the elements between two specified values.
For example, I have an array that looks like this:
a = ["don't want", "don't want", "Start", "want", "want", "Stop", "don't want", "Start", "want", "Stop", "don't want"]
I want to call a method on the a array that captures the elements between "Start" and "Stop" (that includes the "Start" and "Stop" elements). The resulting array should look like this:
[["Start", "want", "want", "Stop"], ["Start", "want", "Stop"]]
I could not find a method like this, so I tried writing one:
class Array
def group_by_start_and_stop(start = "Start", stop = "Stop")
main_array = []
sub_array = []
group_this_element = false
each do |e|
group_this_element = true if e == start
sub_array << e if group_this_element
if group_this_element and e == stop
main_array << sub_array
sub_array = []
group_this_element = false
end
end
main_array
end
end
This works, but it seems perhaps unnecessarily verbose to me. So I have two questions: Does a similar method already exist? If not, are there ways to make my group_by_start_and_stop method better?
['Start', 'want', 'Start', 'want', 'Stop', 'Stop'])? Is that a Start/Stop inside another Start/Stop, overlapping intervals, or invalid?