Skip to content

Commit

Permalink
Merge pull request #7971 from dgraham/hash-replace
Browse files Browse the repository at this point in the history
Implement HashWithIndifferentAccess#replace so key? works correctly.
  • Loading branch information
rafaelfranca committed Oct 26, 2012
2 parents 6ac33f9 + f38e752 commit f078f91
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 0 deletions.
2 changes: 2 additions & 0 deletions activesupport/CHANGELOG.md
@@ -1,5 +1,7 @@
## Rails 4.0.0 (unreleased) ## ## Rails 4.0.0 (unreleased) ##


* Implement HashWithIndifferentAccess#replace so key? works correctly. *David Graham*

* Hash#extract! returns only those keys that present in the receiver. * Hash#extract! returns only those keys that present in the receiver.


{:a => 1, :b => 2}.extract!(:a, :x) # => {:a => 1} {:a => 1, :b => 2}.extract!(:a, :x) # => {:a => 1}
Expand Down
Expand Up @@ -204,6 +204,14 @@ def reverse_merge!(other_hash)
replace(reverse_merge( other_hash )) replace(reverse_merge( other_hash ))
end end


# Replaces the contents of this hash with other_hash.
#
# h = { "a" => 100, "b" => 200 }
# h.replace({ "c" => 300, "d" => 400 }) #=> {"c"=>300, "d"=>400}
def replace(other_hash)
super(self.class.new_from_hash_copying_default(other_hash))
end

# Removes the specified key from the hash. # Removes the specified key from the hash.
def delete(key) def delete(key)
super(convert_key(key)) super(convert_key(key))
Expand Down
12 changes: 12 additions & 0 deletions activesupport/test/core_ext/hash_ext_test.rb
Expand Up @@ -428,6 +428,18 @@ def test_indifferent_merging
assert_equal 2, hash['b'] assert_equal 2, hash['b']
end end


def test_indifferent_replace
hash = HashWithIndifferentAccess.new
hash[:a] = 42

replaced = hash.replace(b: 12)

assert hash.key?('b')
assert !hash.key?(:a)
assert_equal 12, hash[:b]
assert_same hash, replaced
end

def test_indifferent_merging_with_block def test_indifferent_merging_with_block
hash = HashWithIndifferentAccess.new hash = HashWithIndifferentAccess.new
hash[:a] = 1 hash[:a] = 1
Expand Down

0 comments on commit f078f91

Please sign in to comment.