aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/core_ext/hash/transform_values.rb
blob: 6ff7e9121273b27d7799f27aceacba2c6fa8412b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Hash
  # Returns a new hash with the results of running +block+ once for every value.
  # The keys are unchanged.
  #
  #   { a: 1, b: 2, c: 3 }.transform_values { |x| x * 2 }
  #   # => { a: 2, b: 4, c: 6 }
  def transform_values(&block)
    result = self.class.new
    each do |key, value|
      result[key] = yield(value)
    end
    result
  end

  # Destructive +transform_values+
  def transform_values!
    each do |key, value|
      self[key] = yield(value)
    end
  end
end