Skip to content

Commit

Permalink
revises implementation of AS::OrderedHash#merge!
Browse files Browse the repository at this point in the history
  • Loading branch information
fxn committed Jun 13, 2010
1 parent 3359af6 commit 36143d2
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 21 deletions.
2 changes: 1 addition & 1 deletion activesupport/CHANGELOG
@@ -1,6 +1,6 @@
*Rails 3.0.0 [Release Candidate] (unreleased)*

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

* 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: 6 additions & 4 deletions activesupport/lib/active_support/ordered_hash.rb
Expand Up @@ -130,10 +130,12 @@ def shift
end

def merge!(other_hash)
if block_given?
other_hash.each {|k,v| self[k] = yield(k, self[k], v) }
else
other_hash.each {|k,v| self[k] = v }
other_hash.each do |k, v|
if block_given? && key?(k)
self[k] = yield k, self[k], v
else
self[k] = v
end
end
self
end
Expand Down
33 changes: 17 additions & 16 deletions activesupport/test/ordered_hash_test.rb
Expand Up @@ -144,28 +144,29 @@ def test_merge
end

def test_merge_with_block
other_hash = ActiveSupport::OrderedHash.new
other_hash['white'] = 'ff'
other_hash['black'] = '00'
merged = @ordered_hash.merge(other_hash) do |key, old_value, new_value|
new_value * 3
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 'ffffff', merged['white']
assert_equal '000000', merged['black']

assert_nil @ordered_hash['white']
assert_nil @ordered_hash['black']
assert_equal 0, merged[:a]
assert_equal 3, merged[:b]
assert_equal 7, merged[:c]
end

def test_merge_bang_with_block
other_hash = ActiveSupport::OrderedHash.new
other_hash['white'] = 'ff'
other_hash['black'] = '00'
@ordered_hash.merge!(other_hash) do |key, old_value, new_value|
new_value * 3
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 'ffffff', @ordered_hash['white']
assert_equal '000000', @ordered_hash['black']

assert_equal 4, hash[:a]
assert_equal 0, hash[:b]
assert_equal 7, hash[:c]
end

def test_shift
Expand Down

0 comments on commit 36143d2

Please sign in to comment.