mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Added Hash#deep_dup function which performs deep duplication on given hash
This commit is contained in:
parent
cfbe595831
commit
5071b727b4
3 changed files with 27 additions and 0 deletions
|
@ -1,5 +1,6 @@
|
|||
require 'active_support/core_ext/hash/conversions'
|
||||
require 'active_support/core_ext/hash/deep_merge'
|
||||
require 'active_support/core_ext/hash/deep_dup'
|
||||
require 'active_support/core_ext/hash/diff'
|
||||
require 'active_support/core_ext/hash/except'
|
||||
require 'active_support/core_ext/hash/indifferent_access'
|
||||
|
|
11
activesupport/lib/active_support/core_ext/hash/deep_dup.rb
Normal file
11
activesupport/lib/active_support/core_ext/hash/deep_dup.rb
Normal file
|
@ -0,0 +1,11 @@
|
|||
class Hash
|
||||
# Returns a deep copy of hash.
|
||||
def deep_dup
|
||||
duplicate = self.dup
|
||||
duplicate.each_pair do |k,v|
|
||||
tv = duplicate[k]
|
||||
duplicate[k] = tv.is_a?(Hash) && v.is_a?(Hash) ? tv.deep_dup : v
|
||||
end
|
||||
duplicate
|
||||
end
|
||||
end
|
|
@ -316,6 +316,21 @@ class HashExtTest < Test::Unit::TestCase
|
|||
assert_equal expected, hash_1
|
||||
end
|
||||
|
||||
def test_deep_dup
|
||||
hash = { :a => { :b => 'b' } }
|
||||
dup = hash.deep_dup
|
||||
dup[:a][:c] = 'c'
|
||||
assert_equal nil, hash[:a][:c]
|
||||
assert_equal 'c', dup[:a][:c]
|
||||
end
|
||||
|
||||
def test_deep_dup_initialize
|
||||
zero_hash = Hash.new 0
|
||||
hash = { :a => zero_hash }
|
||||
dup = hash.deep_dup
|
||||
assert_equal 0, dup[:a][44]
|
||||
end
|
||||
|
||||
def test_store_on_indifferent_access
|
||||
hash = HashWithIndifferentAccess.new
|
||||
hash.store(:test1, 1)
|
||||
|
|
Loading…
Reference in a new issue