From: matz@... Date: 2014-05-17T06:26:06+00:00 Subject: [ruby-core:62633] [ruby-trunk - Feature #9826] [Feedback] Enumerable#slice_between Issue #9826 has been updated by Yukihiro Matsumoto. Status changed from Open to Feedback I understand the use-case, and I'd like to add the feature. But slice_between does not describe what it does. Try another name. Matz. ---------------------------------------- Feature #9826: Enumerable#slice_between https://bugs.ruby-lang.org/issues/9826#change-46769 * Author: Akira Tanaka * Status: Feedback * Priority: Normal * Assignee: * Category: * Target version: ---------------------------------------- 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. * ruby-talk:370132 Dave Thomas and James Edward Gray II * http://d.hatena.ne.jp/keyesberry/20120107/p1 (in Japanese) `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. * ruby-talk:359255 split logs where interval is 30s or more. * http://stackoverflow.com/questions/6258971/how-do-i-return-a-group-of-sequential-numbers-that-might-exist-in-an-array * ruby-talk:415057 collects same elements. (Enumerable#chunk can be used, though.) Any idea? ---Files-------------------------------- slice_between.patch (10 KB) slice_between2.patch (9.7 KB) -- https://bugs.ruby-lang.org/