在Ruby中,在找到不同的元素之前,我如何对数组中的元素进行分组?例如:
array = [1, 1, 2, 3, 3, 1, 5, 6, 2]
我想迭代它,但直到下一个元素不同。我不想对它进行排序,因为它仍然需要按顺序排列。所以,如果我要浏览这个数组:
for [1, 1] do X
for [2] do Y
for [3, 3] do Z
for [1] do X
答案 0 :(得分:4)
这是另一种方式:
array = [1, 1, 2, 3, 3, 1, 5, 6, 2]
array.group_by(&:itself).values
# => [[1, 1, 1], [2, 2], [3, 3], [5], [6]]
查看#itself
方法。
如果你上面没有问过,那么#slice_when
就是你要走的路:
array.slice_when { |i,j| i != j }.to_a
# => [[1, 1], [2], [3, 3], [1], [5], [6], [2]]
array.slice_when { |i,j| i != j }.each { |n| p "do_something_with_#{n}" }
# "do_something_with_[1, 1]"
# "do_something_with_[2]"
# "do_something_with_[3, 3]"
# "do_something_with_[1]"
# "do_something_with_[5]"
# "do_something_with_[6]"
# "do_something_with_[2]"