Skip to content

End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Enumerable#slice_after

slice_after(pattern) → enumerator
slice_after {|array| ... } → enumerator

With argument pattern, returns an enumerator that uses the pattern to partition elements into arrays (“slices”). An element ends the current slice if element === pattern:

Example
a = %w[foo bar fop for baz fob fog bam foy]
e = a.slice_after(/ba/) # => #<Enumerator: ...>
e.each {|array| p array }

Output:

Example
["foo", "bar"]
["fop", "for", "baz"]
["fob", "fog", "bam"]
["foy"]

With a block, returns an enumerator that uses the block to partition elements into arrays. An element ends the current slice if its block return is a truthy value:

Example
e = (1..20).slice_after {|i| i % 4 == 2 } # => #<Enumerator: ...>
e.each {|array| p array }

Output:

Example
[1, 2]
[3, 4, 5, 6]
[7, 8, 9, 10]
[11, 12, 13, 14]
[15, 16, 17, 18]
[19, 20]

Other methods of the Enumerator class and Enumerable module, such as map, etc., are also usable.

For example, continuation lines (lines end with backslash) can be concatenated as follows:

Example
lines = ["foo\n", "bar\\\n", "baz\n", "\n", "qux\n"]
e = lines.slice_after(/(?<!\\)\n\z/)
p e.to_a
#=> [["foo\n"], ["bar\\\n", "baz\n"], ["\n"], ["qux\n"]]
p e.map {|ll| ll[0...-1].map {|l| l.sub(/\\\n\z/, "") }.join + ll.last }
#=>["foo\n", "barbaz\n", "\n", "qux\n"]
See also #select #slice_before #reverse_each #slice_when also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.0