Skip to content
Browse files

Merge pull request #1740 from Antiarchitect/2-3-stable

Fix OrderedHash merging with block given.
  • Loading branch information...
2 parents 1aae5e7 + b1c36b7 commit 8d02083f231b6d6f0cde891a68e4870108203605 @josevalim josevalim committed Jun 17, 2011
Showing with 33 additions and 3 deletions.
  1. +7 −3 activesupport/lib/active_support/ordered_hash.rb
  2. +26 −0 activesupport/test/ordered_hash_test.rb
View
10 activesupport/lib/active_support/ordered_hash.rb
@@ -130,14 +130,18 @@ 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] = key?(k) ? yield(k, self[k], v) : v }
+ else
+ other_hash.each { |k, v| self[k] = v }
+ end
self
end
alias_method :update, :merge!
- 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.
View
26 activesupport/test/ordered_hash_test.rb
@@ -147,6 +147,32 @@ def test_merge
assert_equal @ordered_hash.keys, merged.keys
end
+ def test_merge_with_block
+ hash = ActiveSupport::OrderedHash.new
+ hash[:a] = 0
+ hash[:b] = 0
+ merged = hash.merge(:b => 2, :c => 7) do |key, old_value, new_value|
+ new_value + 1
+ end
+
+ assert_equal 0, merged[:a]
+ assert_equal 3, merged[:b]
+ assert_equal 7, merged[:c]
+ end
+
+ def test_merge_bang_with_block
+ hash = ActiveSupport::OrderedHash.new
+ hash[:a] = 0
+ hash[:b] = 0
+ hash.merge!(:a => 1, :c => 7) do |key, old_value, new_value|
+ new_value + 3
+ end
+
+ assert_equal 4, hash[:a]
+ assert_equal 0, hash[:b]
+ assert_equal 7, hash[:c]
+ end
+
def test_shift
pair = @ordered_hash.shift
assert_equal [@keys.first, @values.first], pair

0 comments on commit 8d02083

Please sign in to comment.
Something went wrong with that request. Please try again.