## Feature #10769

### Negative counterpart to Enumerable#slice_when

Status:
Closed
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:67738]

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.

#### Updated by austin (Austin Ziegler)almost 6 years ago

What about `.slice_unless`?

#### Updated by sawa (Tsuyoshi Sawada)almost 6 years ago

Austin Ziegler wrote:

What about `.slice_unless`?

The point of my proposal is that this negation is a negation if you look from the point of view of `slice_when`, but it is in fact more natural than `slice_when`, so that it should not be considered as negation of the latter (Rather, `slice_when` should be considered the negation of this method.). But "unless" carries the meaning of negation.

#### Updated by matz (Yukihiro Matsumoto)over 5 years ago

#chunk_while looks good to me. Go ahead.

Matz.

#### Updated by akr (Akira Tanaka)over 5 years ago

• Status changed from Open to Closed

Applied in changeset r50889.

• enum.c (enum_chunk_while): New method Enumerable#chunk_while. [ruby-core:67738] [Feature #10769] proposed by Tsuyoshi Sawada.

Also available in: Atom PDF