I have the following array:
arr = [0, 1, 1, 2, 3, 1, 0, 0, 1]
在不改变值的顺序的情况下,我需要在每个 0
出现的地方将 arr
细分为较小的数组,以便结果如下:
arr = [ [0, 1, 1, 2, 3, 1], [0], [0, 1] ]
如果
arr
是一个字符串,我可以使用.split("0")
,然后在每个子数组前添加分隔符。对于数组来说,在纯Ruby中最有效的等效函数是什么?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+/
上拆分?slice_before
是我需要的。我一直在尝试不使用ActiveSupport来完成它,但这仍然非常有用。谢谢! - DJK
Array
的复杂使用。我会思考在解析时是否有更适合的数据类型可用,而不是将数组转换为嵌套数组。如果不知道这将在哪里使用,很难提供建议。但我会考虑使用对象构建树形结构。例如,每行都成为自己的对象,并具有其父对象和子对象的信息。您需要保留顺序,这可以使用子对象作为对象数组来完成。 - Lee-Jon