Sha256: b4465e9c1ab45c10081bab4f15c0b6da2829d31c8d5ee2f5119d1439de0e9814

Contents?: true

Size: 712 Bytes

Versions: 3

Compression:

Stored size: 712 Bytes

Contents

class Hash
  # Allows you to map the values of a hash. The original
  # keys will be retained.
  # 
  # ```ruby
  # {foo: 1, bar: 2}.map_values {|value| value * 2 } #=> {foo: 2, bar: 4}
  # ```
  #
  # The original hash is not mutated.
  def map_values
    Hash.new.tap do |result|
      self.each do |key, value|
        result[key] = yield(value)
      end
    end
  end

  # The same as {Hash#map_values}, except mutates and returns the original hash.
  # 
  # ```ruby
  # hash = {foo: 1, bar: 2}
  # hash.map_values {|value| value * 2 }
  # hash #=> {foo: 2, bar: 4}
  # ```
  def map_values!
    self.tap do |hash|
      hash.each do |key, value|
        hash[key] = yield(value)
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
tfg_support-1.1.1 lib/tfg/support/core_ext/hash/map_values.rb
tfg_support-1.0.1 lib/tfg/support/core_ext/hash/map_values.rb
tfg_support-1.0.0 lib/tfg/support/core_ext/hash/map_values.rb