Sha256: 078bbdef9def7f431f479d1bbd03e2e0fcbbf22ab459114363fd3c1b30a710f3

Contents?: true

Size: 937 Bytes

Versions: 1

Compression:

Stored size: 937 Bytes

Contents

# encoding: utf-8

module Nanoc3::EnumerableExtensions

  module GroupBy

    # Returns a hash, which keys are evaluated result from the block, and
    # values are arrays of elements in enum corresponding to the key. This
    # method is provided for backward compatibility with Ruby 1.8.6 and lower,
    # since {#group_by} is only available in 1.8.7 and higher.
    #
    # @yieldparam [Object] obj The object to classify
    #
    # @return [Hash]
    #
    # @example Grouping integers by rest by division through 3
    #
    #   (1..6).group_by { |i| i % 3 }
    #   # => { 0 => [3, 6], 1 => [1, 4], 2 => [2, 5] }
    def group_by
      groups = {}
      each do |item|
        key = yield(item)

        groups[key] ||= []
        groups[key] << item
      end
      groups
    end

  end

end

module Enumerable

  if !Enumerable.instance_methods.include?('group_by')
    include Nanoc3::EnumerableExtensions::GroupBy
  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
nanoc3-3.1.0a2 lib/nanoc3/base/core_ext/enumerable.rb