Sha256: 79053ccd0b609da0d54ec8ebe3bb13662ad8232670bf245aba7d3185258527ee

Contents?: true

Size: 697 Bytes

Versions: 19

Compression:

Stored size: 697 Bytes

Contents

module Hash::MapToHash
  # Update all values in a hash.
  # Passes +key,value+ pairs to its block, replaces the pair 
  # with the block's return value.
  def map_to_hash(options = {}, &block)
    Hash.new.tap do |result|
      self.each_pair do |key,value|
        value = _deep_convert(value, block) if options[:deep]
        new_key, new_value = block.call(key, value)
        result[new_key] = new_value
      end
    end
  end

  private

  def _deep_convert(value, block)
    case value
    when Hash
      value.map_to_hash({ :deep => true }, &block)
    when Array
      value.map { |item| _deep_convert(item, block) }
    else
      value
    end
  end

  Hash.send(:include, self)
end

Version data entries

19 entries across 19 versions & 1 rubygems

Version Path
guignol-0.3.16 lib/core_ext/hash/map_to_hash.rb
guignol-0.3.15 lib/core_ext/hash/map_to_hash.rb
guignol-0.3.14 lib/core_ext/hash/map_to_hash.rb
guignol-0.3.13 lib/core_ext/hash/map_to_hash.rb
guignol-0.3.12 lib/core_ext/hash/map_to_hash.rb
guignol-0.3.10 lib/core_ext/hash/map_to_hash.rb
guignol-0.3.9 lib/core_ext/hash/map_to_hash.rb
guignol-0.3.8 lib/core_ext/hash/map_to_hash.rb
guignol-0.3.7 lib/core_ext/hash/map_to_hash.rb
guignol-0.3.6.2 lib/core_ext/hash/map_to_hash.rb
guignol-0.3.6.1 lib/core_ext/hash/map_to_hash.rb
guignol-0.3.6 lib/core_ext/hash/map_to_hash.rb
guignol-0.3.5.1 lib/core_ext/hash/map_to_hash.rb
guignol-0.3.5 lib/core_ext/hash/map_to_hash.rb
guignol-0.3.4 lib/core_ext/hash/map_to_hash.rb
guignol-0.3.3 lib/core_ext/hash/map_to_hash.rb
guignol-0.3.2 lib/core_ext/hash/map_to_hash.rb
guignol-0.3.1 lib/core_ext/hash/map_to_hash.rb
guignol-0.3.0 lib/core_ext/hash/map_to_hash.rb