Skip to content

Commit

Permalink
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implement Enumerable#slice_after
Browse files Browse the repository at this point in the history
jsyeo committed Mar 11, 2015
1 parent a511153 commit ef0d44d
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 additions & 0 deletions kernel/common/enumerable.rb
Original file line number Diff line number Diff line change
@@ -160,6 +160,31 @@ def slice_before(arg = undefined, &block)
end
end

def slice_after(pattern = undefined, &block)
pattern_given = !undefined.equal?(pattern)

raise ArgumentError, "cannot pass both pattern and block" if pattern_given && block_given?
raise ArgumentError, "wrong number of arguments (0 for 1)" if !pattern_given && !block_given?

block = Proc.new { |elem| pattern === elem } if pattern_given

Enumerator.new do |yielder|
accumulator = nil
each do |elem|
end_chunk = block.yield(elem)
accumulator ||= []
if end_chunk
accumulator << elem
yielder.yield accumulator
accumulator = nil
else
accumulator << elem
end
end
yielder.yield accumulator if accumulator
end
end

def to_a(*arg)
ary = []
each(*arg) do

0 comments on commit ef0d44d

Please sign in to comment.