按特定值分组Ruby数组

Gle*_*enn 10 ruby arrays

我有一个数组,我只想选择两个指定值之间的元素.

例如,我有一个如下所示的数组:

a = ["don't want", "don't want", "Start", "want", "want", "Stop", "don't want", "Start", "want", "Stop", "don't want"]
Run Code Online (Sandbox Code Playgroud)

我想在一个数组上调用一个方法来捕获"开始"和"停止"之间的元素(包括"开始"和"停止"元素).生成的数组应如下所示:

[["Start", "want", "want", "Stop"], ["Start", "want", "Stop"]]
Run Code Online (Sandbox Code Playgroud)

我找不到像这样的方法,所以我尝试写一个:

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
Run Code Online (Sandbox Code Playgroud)

这有效,但似乎对我来说可能是不必要的冗长.所以我有两个问题:类似的方法是否已经存在?如果没有,有没有办法让我的group_by_start_and_stop方法更好?

Jea*_*ano 7

这是触发器很有用的完美示例!

a.select {|i| true if (i=="Start")..(i=="Stop")}.slice_before("Start").to_a
Run Code Online (Sandbox Code Playgroud)

不是超级知名的功能,但还是很酷!与它一起使用slice_before,你得到你想要的!


Chu*_*ckE 1

a.each_with_index.select{|s, i| s.eql?("Start") or s.eql?("Stop")}
                 .map{|s, i| i}
                 .each_slice(2)
                 .map{|s, f| a[s..f]}
Run Code Online (Sandbox Code Playgroud)