Skip to content
Permalink
Browse files

Merge pull request #737 from kostya/slice_before

Enumerable#slice_before from rubinius
  • Loading branch information
alex committed May 27, 2013
2 parents a4a85a4 + 5b9137a commit 78f5ca1eb98d28fa9431d676bd1da74562e85e8a
Showing with 31 additions and 6 deletions.
  1. +31 −0 lib-topaz/enumerable.rb
  2. +0 −6 spec/tags/core/enumerable/slice_before_tags.txt
@@ -470,4 +470,35 @@ def chunk(initial_state = nil, &original_block)
yielder.yield [previous, accumulate] unless accumulate.empty?
end
end

def slice_before(*args, &block)
arg = nil
if block
raise ArgumentError.new("wrong number of arguments (#{args.size} for 0..1)") if args.size > 1
if args.size == 1
has_init = true
arg = args[0]
end
else
raise ArgumentError.new("wrong number of arguments (#{args.size} for 1)") if args.size > 1
raise ArgumentError.new("wrong number of arguments (0 for 1)") if args.empty?
arg = args[0]
block = Proc.new{ |elem| arg === elem }
end
::Enumerator.new do |yielder|
init = arg.dup if has_init
accumulator = nil
each do |elem|
start_new = has_init ? block.yield(elem, init) : block.yield(elem)
if start_new
yielder.yield accumulator if accumulator
accumulator = [elem]
else
accumulator ||= []
accumulator << elem
end
end
yielder.yield accumulator if accumulator
end
end
end

This file was deleted.

0 comments on commit 78f5ca1

Please sign in to comment.
You can’t perform that action at this time.