Skip to content

Commit

Permalink
Support passing a block to ActiveSupport::OrderedHash's merge and mer…
Browse files Browse the repository at this point in the history
…ge! [#4838 state:committed]

For better consistency with Ruby's own Hash implementation.

Signed-off-by: Xavier Noria <fxn@hashref.com>
  • Loading branch information
mudge authored and fxn committed Jun 13, 2010
1 parent a087bc8 commit 58e21a4
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
2 changes: 2 additions & 0 deletions activesupport/CHANGELOG
@@ -1,5 +1,7 @@
*Rails 3.0.0 [Release Candidate] (unreleased)*

* Ruby 1.9 compatibility: ActiveSupport::OrderedHash#merge and #merge! accept a block. #4838 [Paul Mucur]

* Date#since, #ago, #beginning_of_day, #end_of_day, and #xmlschema honor now the user time zone if set. [Geoff Buesing]


Expand Down
10 changes: 7 additions & 3 deletions activesupport/lib/active_support/ordered_hash.rb
Expand Up @@ -130,12 +130,16 @@ def shift
end

def merge!(other_hash)
other_hash.each {|k,v| self[k] = v }
if block_given?
other_hash.each {|k,v| self[k] = yield(k, self[k], v) }
else
other_hash.each {|k,v| self[k] = v }
end
self
end

def merge(other_hash)
dup.merge!(other_hash)
def merge(other_hash, &block)
dup.merge!(other_hash, &block)
end

# When replacing with another hash, the initial order of our keys must come from the other hash -ordered or not.
Expand Down
13 changes: 13 additions & 0 deletions activesupport/test/ordered_hash_test.rb
Expand Up @@ -142,9 +142,22 @@ def test_merge
assert_equal merged.length, @ordered_hash.length + other_hash.length
assert_equal @keys + ['purple', 'violet'], merged.keys

another_hash = ActiveSupport::OrderedHash.new
another_hash['white'] = 'ff'
another_hash['black'] = '00'
merged_with_block = @ordered_hash.merge(another_hash) do |key, old_value, new_value|
new_value * 3
end
assert_equal 'ffffff', merged_with_block['white']
assert_equal '000000', merged_with_block['black']

@ordered_hash.merge! other_hash
assert_equal @ordered_hash, merged
assert_equal @ordered_hash.keys, merged.keys

@ordered_hash.merge! another_hash
assert_equal 'ffffff', merged_with_block['white']
assert_equal '000000', merged_with_block['black']
end

def test_shift
Expand Down

1 comment on commit 58e21a4

@fxn
Copy link
Member

@fxn fxn commented on 58e21a4 Jun 13, 2010

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See 36143d2 though.

Please sign in to comment.