Sha256: d108d732176f199029b04d5b03b6d7d174e7fa3a40d2c8988f3ecc88d844bf13

Contents?: true

Size: 909 Bytes

Versions: 5

Compression:

Stored size: 909 Bytes

Contents

module Enumerable # Remove this as soon as it is integrated into ActiveSupport.
  # Associates keys with values and returns a Hash.
  #
  # If you have an enumerable of keys and want to associate them with values,
  # pass a block that returns a value for the key:
  #
  #   [1, 2, 3].associate { |i| i ** 2 }
  #   # => { 1 => 1, 2 => 4, 3 => 9 }
  #
  #   %w( tender love ).associate &:capitalize
  #   # => {"tender"=>"Tender", "love"=>"Love"}
  #
  # If you have an enumerable key/value pairs and want to associate them,
  # omit the block and you'll get a hash in return:
  #
  #   [[1, 2], [3, 4]].associate
  #   # => { 1 => 2, 3 => 4 }
  def associate(mapping = {})
    if block_given?
      each_with_object(mapping) do |key, object|
        object[key] = yield(key)
      end
    else
      each_with_object(mapping) do |(key, value), object|
        object[key] = value
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
mongoid-time_range-0.4.1 lib/enumerable/associate.rb
mongoid-time_range-0.4.0 lib/enumerable/associate.rb
mongoid-time_range-0.3.0 lib/enumerable/associate.rb
mongoid-time_range-0.2.0 lib/enumerable/associate.rb
mongoid-time_range-0.1.0 lib/enumerable/associate.rb