Skip to content

Commit

Permalink
Port over jruby's Enumerable#slice_when
Browse files Browse the repository at this point in the history
  • Loading branch information
tak1n committed May 27, 2015
1 parent 7111811 commit f21d58d
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 6 deletions.
31 changes: 29 additions & 2 deletions kernel/common/enumerable.rb
Expand Up @@ -185,6 +185,33 @@ def slice_after(pattern = undefined, &block)
end
end

def slice_when(&block)
raise ArgumentError, "wrong number of arguments (0 for 1)" unless block_given?

Enumerator.new do |enum|
ary = nil
last_after = nil
each_cons(2) do |before, after|
last_after = after
match = block.call before, after

ary ||= []
if match
ary << before
enum.yield ary
ary = []
else
ary << before
end
end

unless ary.nil?
ary << last_after
enum.yield ary
end
end
end

def to_a(*arg)
ary = []
each(*arg) do
Expand Down Expand Up @@ -443,8 +470,8 @@ def each_cons(num)
unless block_given?
return to_enum(:each_cons, num) do
enum_size = enumerator_size
if enum_size.nil?
nil
if enum_size.nil?
nil
elsif enum_size == 0
0
else
Expand Down
4 changes: 0 additions & 4 deletions spec/tags/ruby/core/enumerable/slice_when_tags.txt

This file was deleted.

0 comments on commit f21d58d

Please sign in to comment.