簡體   English   中英

如何使用分隔符將Ruby數組拆分為不等大小的子數組

[英]How to split a Ruby array into subarrays of unequal size using a delimiter

我有以下數組:

arr = [0, 1, 1, 2, 3, 1, 0, 0, 1]

在不改變值的順序的情況下,我需要在每次出現0arr細分為更小的數組,這樣結果將是:

arr = [ [0, 1, 1, 2, 3, 1], [0], [0, 1] ]

如果arr是一個字符串,我可以使用.split("0")然后將分隔符添加到每個子數組。 普通Ruby中數組中.split()最有效的等價物是什么?

Enumerable#slice_before做了這件事:

arr = [0, 1, 1, 2, 3, 1, 0, 0, 1]
p arr.slice_before(0).to_a
# => [[0, 1, 1, 2, 3, 1], [0], [0, 1]]

看到它在repl.it: https://repl.it/FBhg

由於ActiveSupport在Ruby中定義了一個Array#split方法 ,我們可以將它作為一個起點:

class Array
  def split(value = nil)
    arr = dup
    result = []
    if block_given?
      while (idx = arr.index { |i| yield i })
        result << arr.shift(idx)
        arr.shift
      end
    else
      while (idx = arr.index(value))
        result << arr.shift(idx)
        arr.shift
      end
    end
    result << arr
  end
end

# then, using the above to achieve your goal:
arr = [0, 1, 1, 2, 3, 1, 0, 0, 1]
arr.split(0).map { |sub| sub.unshift(0) }
# => [[0], [0, 1, 1, 2, 3, 1], [0], [0, 1]] 

請注意,您對算法的語言短語(分割和前置)就是這里發生的事情,但您的預期輸出是不同的(由於split工作方式,還有一個額外的零)。

你想在每個零之前拆分嗎? 為此你可以使用slice_before

你想分裂但刪除空數組嗎? 這可以在前置之前用快速compact完成,但是你會失去[0]子陣列。

你想拆分但是如果空的話就放下第一個元素嗎?

你想拆分/0+/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM