Sha256: 48a1d9dc54e87ff453bcbf22c9c246b006745c2215ddb7531a6317fc83b503fd

Contents?: true

Size: 1.31 KB

Versions: 69

Compression:

Stored size: 1.31 KB

Contents

unless Enumerable.method_defined? :chunk
  require 'backports/1.9.1/enumerator/new'

  module Enumerable
    def chunk(initial_state = nil, &original_block)
      raise ArgumentError, "no block given" unless block_given?
      ::Enumerator.new do |yielder|
        previous = nil
        accumulate = []
        block = initial_state.nil? ? original_block : Proc.new{|val| original_block.call(val, initial_state.clone)}
        each do |val|
          key = block.call(val)
          if key.nil? || (key.is_a?(Symbol) && key.to_s[0,1] == "_")
            yielder.yield [previous, accumulate] unless accumulate.empty?
            accumulate = []
            previous = nil
            case key
            when nil, :_separator
            when :_alone
              yielder.yield [key, [val]]
            else
              raise RuntimeError, "symbol beginning with an underscore are reserved"
            end
          else
            if previous.nil? || previous == key
              accumulate << val
            else
              yielder.yield [previous, accumulate] unless accumulate.empty?
              accumulate = [val]
            end
            previous = key
          end
        end
        # what to do in case of a break?
        yielder.yield [previous, accumulate] unless accumulate.empty?
      end
    end
  end
end

Version data entries

69 entries across 69 versions & 5 rubygems

Version Path
backports-3.25.0 lib/backports/1.9.2/enumerable/chunk.rb
backports-3.24.1 lib/backports/1.9.2/enumerable/chunk.rb
backports-3.24.0 lib/backports/1.9.2/enumerable/chunk.rb
backports-3.23.0 lib/backports/1.9.2/enumerable/chunk.rb
backports-3.22.1 lib/backports/1.9.2/enumerable/chunk.rb
backports-3.22.0 lib/backports/1.9.2/enumerable/chunk.rb
backports-3.21.0 lib/backports/1.9.2/enumerable/chunk.rb
backports-3.20.2 lib/backports/1.9.2/enumerable/chunk.rb
backports-3.20.1 lib/backports/1.9.2/enumerable/chunk.rb
backports-3.20.0 lib/backports/1.9.2/enumerable/chunk.rb
backports-3.19.0 lib/backports/1.9.2/enumerable/chunk.rb
backports-3.18.2 lib/backports/1.9.2/enumerable/chunk.rb
backports-3.18.1 lib/backports/1.9.2/enumerable/chunk.rb
backports-3.18.0 lib/backports/1.9.2/enumerable/chunk.rb
files.com-1.0.55 docs/vendor/bundle/ruby/2.5.0/gems/backports-3.12.0/lib/backports/1.9.2/enumerable/chunk.rb
backports-3.17.2 lib/backports/1.9.2/enumerable/chunk.rb
backports-3.17.1 lib/backports/1.9.2/enumerable/chunk.rb
backports-3.17.0 lib/backports/1.9.2/enumerable/chunk.rb
backports-3.16.1 lib/backports/1.9.2/enumerable/chunk.rb
backports-3.16.0 lib/backports/1.9.2/enumerable/chunk.rb