Feature #10769
closedNegative counterpart to Enumerable#slice_when
Description
It seems to me that most useful cases of Enumerable#slice_when
involve a negative condition inside the block. That observation seems to be confirmed by the official examples in http://docs.ruby-lang.org/ja/2.2.0/method/Enumerable/i/slice_when.html. In these examples, the conditions inside the block are negations of what would is intended (which is expressed in the comment above each code).
# 1ずつ増加する部分配列ごとに分ける。
[1,2,4,9,10,11,12,15,16,19,20,21]
.slice_when{|i, j| i + 1 != j}.to_a # => [[1, 2], [4], [9, 10, 11, 12], [15, 16], [19, 20, 21]]
# ソート済の配列を近い値(差が6以内)の部分配列ごとに分ける。
[3, 11, 14, 25, 28, 29, 29, 41, 55, 57]
.slice_when{|i, j| 6 < j - i}.to_a # => [[3], [11, 14], [25, 28, 29, 29], [41], [55, 57]]
# 増加のみの部分配列ごとに分ける。
[0, 9, 2, 2, 3, 2, 7, 5, 9, 5]
.slice_when{|i, j| i > j}.to_a # => [[0, 9], [2, 2, 3], [2, 7], [5, 9], [5]]
# 隣り合う偶数同士、奇数同士の部分配列ごとに分ける。
[7, 5, 9, 2, 0, 7, 9, 4, 2, 0]
.slice_when{|i, j| i.even? != j.even?}.to_a # => [[7, 5, 9], [2, 0], [7, 9], [4, 2, 0]]
I propose that there should be a method on Enumerable
that works like slice_when
except that it works with the block negatively as compared to slice_when
. Let us call this method Enumerable#chunk_while
. Then, the examples above would be written more naturally without having a negative notion in the blocks.
# 1ずつ増加する部分配列ごとに分ける。
[1,2,4,9,10,11,12,15,16,19,20,21]
.chunk_while{|i, j| i + 1 == j}.to_a
# ソート済の配列を近い値(差が6以内)の部分配列ごとに分ける。
[3, 11, 14, 25, 28, 29, 29, 41, 55, 57]
.chunk_while{|i, j| j - i <= 6}.to_a
# 増加のみの部分配列ごとに分ける。
[0, 9, 2, 2, 3, 2, 7, 5, 9, 5]
.chunk_while{|i, j| i <= j}.to_a
# 隣り合う偶数同士、奇数同士の部分配列ごとに分ける。
[7, 5, 9, 2, 0, 7, 9, 4, 2, 0]
.chunk_while{|i, j| i.even? == j.even?}.to_a
I am not sure about the method name. There can be a better name.