Sha256: 21c6ddcb5d76eea320b15fb70da13ba166e891cddfaec339f8922b1c24c8722f
Contents?: true
Size: 1.06 KB
Versions: 4
Compression:
Stored size: 1.06 KB
Contents
# Backport from Rails 4.x # https://github.com/rails/rails/blob/4-0-stable/activesupport/lib/active_support/core_ext/object/deep_dup.rb require_relative 'duplicable' class Object # Returns a deep copy of object if it's duplicable. If it's # not duplicable, returns +self+. # # object = Object.new # dup = object.deep_dup # dup.instance_variable_set(:@a, 1) # # object.instance_variable_defined?(:@a) #=> false # dup.instance_variable_defined?(:@a) #=> true def deep_dup duplicable? ? dup : self end end class Array # Returns a deep copy of array. # # array = [1, [2, 3]] # dup = array.deep_dup # dup[1][2] = 4 # # array[1][2] #=> nil # dup[1][2] #=> 4 def deep_dup map(&:deep_dup) end end class Hash # Returns a deep copy of hash. # # hash = { a: { b: 'b' } } # dup = hash.deep_dup # dup[:a][:c] = 'c' # # hash[:a][:c] #=> nil # dup[:a][:c] #=> "c" def deep_dup each_with_object(dup) do |(key, value), hash| hash[key.deep_dup] = value.deep_dup end end end
Version data entries
4 entries across 4 versions & 1 rubygems