Method: Weak::Map#update
- Defined in:
- lib/weak/map.rb
#update(*other_maps) {|key, old_value, new_value| ... } ⇒ self Also known as: merge!
Note:
Weak::Map does not test member equality with ==
or eql?
.
Instead, it always checks strict object equality, so that, e.g.,
different String keys are not considered equal, even if they may
contain the same content.
Merges each of other_maps
into self
; returns self
.
Each argument in other_maps
must be either a Weak::Map, a Hash object
or must be transformable to a Hash by calling each_hash
on it.
With arguments and no block:
- Returns self, after the given maps are merged into it.
- The given maps are merged left to right.
- Each duplicate-key entry’s value overwrites the previous value.
Example:
map = Weak::Map.new
map[:foo] = 0
map[:bar] = 1
h1 = {baz: 3, bar: 4}
h2 = {bam: 5, baz: 6}
map.update(h1, h2)
# => #<Weak::Map {:foo=>0, :bar=>4, :baz=>6, :bam=>5}
With arguments and a block:
- Returns
self
, after the given maps are merged. - The given maps are merged left to right.
- For each duplicate key:
- Calls the block with the key and the old and new values.
- The block’s return value becomes the new value for the entry.
- The block should only return values which are otherwise strongly referenced to ensure that the value is not immediately garbage-collected.
Example:
map = Weak::Map.new
map[:foo] = 0
map[:bar] = 1
h1 = {baz: 3, bar: 4}
h2 = {bam: 5, baz: 6}
map.update(h1, h2) { |key, old_value, new_value| old_value + new_value }
# => #<Weak::Map {:foo=>0, :bar=>5, :baz=>9, :bam=>5}
With no arguments:
- Returns
self
. - The block, if given, is ignored.
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 |
# File 'lib/weak/map.rb', line 733 def update(*other_maps) if block_given? missing = Object.new other_maps.each do |map| _implicit(map).each_pair do |key, value| old_value = fetch(key, missing) value = yield(key, old_value, value) unless missing == old_value self[key] = value end end else other_maps.each do |map| _implicit(map).each_pair do |key, value| self[key] = value end end end self end |