diff options
author | Leo Cassarani <leo.cassarani@me.com> | 2012-09-03 23:13:49 +0100 |
---|---|---|
committer | Leo Cassarani <leo.cassarani@me.com> | 2012-09-05 00:59:29 +0100 |
commit | edab820d9ee5c18780e11752d46d7df73c820ddb (patch) | |
tree | fbe62a00a861fc9fcd1338b48df9df96da4e3c0e /activesupport/test | |
parent | 7995c03dc0e8ff8448427de16c98f77aa8bb6a01 (diff) | |
download | rails-edab820d9ee5c18780e11752d46d7df73c820ddb.tar.gz rails-edab820d9ee5c18780e11752d46d7df73c820ddb.tar.bz2 rails-edab820d9ee5c18780e11752d46d7df73c820ddb.zip |
Extend HashWithIndifferentAccess#update to take an optional block
When a block is passed into the method, it will be invoked for each
duplicated key, with the key in question and the two values as
arguments. The value for the duplicated key in the receiver will
be set to the return value of the block.
This behaviour matches Ruby's long-standing implementation of
Hash#update and is intended to provide a more consistent interface.
HashWithIndifferentAccess#merge is also affected by the change, as it
uses #update internally.
Diffstat (limited to 'activesupport/test')
-rw-r--r-- | activesupport/test/core_ext/hash_ext_test.rb | 23 |
1 files changed, 23 insertions, 0 deletions
diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb index 4dc9f57038..37fdf1c0af 100644 --- a/activesupport/test/core_ext/hash_ext_test.rb +++ b/activesupport/test/core_ext/hash_ext_test.rb @@ -428,6 +428,29 @@ class HashExtTest < ActiveSupport::TestCase assert_equal 2, hash['b'] end + def test_indifferent_merging_with_block + hash = HashWithIndifferentAccess.new + hash[:a] = 1 + hash['b'] = 3 + + other = { 'a' => 4, :b => 2, 'c' => 10 } + + merged = hash.merge(other) { |key, old, new| old > new ? old : new } + + assert_equal HashWithIndifferentAccess, merged.class + assert_equal 4, merged[:a] + assert_equal 3, merged['b'] + assert_equal 10, merged[:c] + + other_indifferent = HashWithIndifferentAccess.new('a' => 9, :b => 2) + + merged = hash.merge(other_indifferent) { |key, old, new| old + new } + + assert_equal HashWithIndifferentAccess, merged.class + assert_equal 10, merged[:a] + assert_equal 5, merged[:b] + end + def test_indifferent_reverse_merging hash = HashWithIndifferentAccess.new('some' => 'value', 'other' => 'value') hash.reverse_merge!(:some => 'noclobber', :another => 'clobber') |