Actions
Feature #9826
closedEnumerable#slice_between
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.
- 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
Actions
Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0