Sha256: fc6f6e465d39aeeca3d05fc5c27f263a8f6a9201abf6591e014bab9f951ab705

Contents?: true

Size: 1.42 KB

Versions: 3

Compression:

Stored size: 1.42 KB

Contents

# frozen_string_literal: true

class Hash
  # Returns a new hash with all keys converted by the block operation.
  # This includes the keys from the root hash and from all
  # nested hashes and arrays.
  #
  #  hash = { person: { name: 'Rob', age: '28' } }
  #
  #  hash.deep_transform_values{ |value| value.to_s.upcase }
  #  # => {person: {name: "ROB", age: "28"}}
  def deep_transform_values(&block)
    _deep_transform_values_in_object(self, &block)
  end

  # Destructively converts all values by using the block operation.
  # This includes the values from the root hash and from all
  # nested hashes and arrays.
  def deep_transform_values!(&block)
    _deep_transform_values_in_object!(self, &block)
  end

  private
    # support methods for deep transforming nested hashes and arrays
    def _deep_transform_values_in_object(object, &block)
      case object
      when Hash
        object.transform_values { |value| _deep_transform_values_in_object(value, &block) }
      when Array
        object.map { |e| _deep_transform_values_in_object(e, &block) }
      else
        yield(object)
      end
    end

    def _deep_transform_values_in_object!(object, &block)
      case object
      when Hash
        object.transform_values! { |value| _deep_transform_values_in_object!(value, &block) }
      when Array
        object.map! { |e| _deep_transform_values_in_object!(e, &block) }
      else
        yield(object)
      end
    end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
activesupport-6.0.0.rc1 lib/active_support/core_ext/hash/deep_transform_values.rb
activesupport-6.0.0.beta3 lib/active_support/core_ext/hash/deep_transform_values.rb
activesupport-6.0.0.beta2 lib/active_support/core_ext/hash/deep_transform_values.rb