Project

General

Profile

Actions

Feature #9826

closed

Enumerable#slice_between

Added by akr (Akira Tanaka) almost 10 years ago. Updated over 9 years ago.

Status:
Closed
Target version:
-
[ruby-core:62499]

Description

I'd like to add a new method, Enumerable#slice_between.

It is similar to Enumerable#slice_before but it can use
not only the element after the slice position
but also the element before the slice position.

enum.slice_between(pattern_before, pattern_after=nil) -> an_enumerator
enum.slice_between {|elt_before, elt_after| bool }    -> an_enumerator

I found several people try to use Enumerable#slice_before for
compacting sequence of integers using hyphens:
1,2,4,9,10,11,12,15,16,19,20,21 to 1,2,4,9-12,15,16,19-21.

slice_before needs state management to do it.
slice_between can be used more easily for this situation:

a = [1,2,4,9,10,11,12,15,16,19,20,21]
p a.slice_between {|i, j| i+1 != j }.map {|a| a.length < 3 ? a : "#{a.first}-#{a.last}" }.join(",")

Or more verbosely as:

a = [1,2,4,9,10,11,12,15,16,19,20,21]
b = a.slice_between {|i, j| i+1 != j }
p b.to_a #=> [[1, 2], [4], [9, 10, 11, 12], [15, 16], [19, 20, 21]]
c = b.map {|a| a.length < 3 ? a : "#{a.first}-#{a.last}" }
p c #=> [[1, 2], [4], "9-12", [15, 16], "19-21"]
d = c.join(",")
p d #=> "1,2,4,9-12,15,16,19-21"

Also, I found several usages for Enumerable#slice_between.

Any idea?


Files

slice_between.patch (10 KB) slice_between.patch akr (Akira Tanaka), 05/10/2014 11:54 AM
slice_between2.patch (9.7 KB) slice_between2.patch akr (Akira Tanaka), 05/12/2014 09:47 AM
slice_between3.patch (9.71 KB) slice_between3.patch akr (Akira Tanaka), 05/18/2014 04:06 AM
slice_when.patch (7.49 KB) slice_when.patch akr (Akira Tanaka), 09/18/2014 04:30 AM
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0