Method: Hanami::Utils::Hash.deep_dup

Defined in:
lib/hanami/utils/hash.rb

.deep_dup(input) ⇒ ::Hash

Deep duplicates hash values

The output of this function is a deep duplicate of the input. Any further modification on the input, won’t be reflected on the output and viceversa.

Examples:

Basic Usage

require 'hanami/utils/hash'

input  = { "a" => { "b" => { "c" => [1, 2, 3] } } }
output = Hanami::Utils::Hash.deep_dup(input)
  # => {"a"=>{"b"=>{"c"=>[1,2,3]}}}

output.class
  # => Hash

# mutations on input aren't reflected on output

input["a"]["b"]["c"] << 4
output.dig("a", "b", "c")
  # => [1, 2, 3]

# mutations on output aren't reflected on input

output["a"].delete("b")
input
  # => {"a"=>{"b"=>{"c"=>[1,2,3,4]}}}

Parameters:

  • input (::Hash)

    the input

Returns:

  • (::Hash)

    the deep duplicate of input

Since:

  • 1.0.1

[View source]

134
135
136
137
138
139
140
141
142
143
# File 'lib/hanami/utils/hash.rb', line 134

def self.deep_dup(input)
  input.transform_values do |v|
    case v
    when ::Hash
      deep_dup(v)
    else
      v.dup
    end
  end
end