instance method
Hash#update
(*::Hash[K, V] other_hashes) -> self
(*::Hash[K, V] other_hashes) { (K key, V oldval, V newval) -> V } -> self
update(*other_hashes) → self
update(*other_hashes) { |key, old_value, new_value| ... } → self
hash.c
View on GitHub ↗
static VALUE
rb_hash_update(int argc, VALUE *argv, VALUE self)
{
struct update_call_args args = {
.hash = self,
.argv = argv,
.argc = argc,
.block_given = rb_block_given_p(),
.iterating = false,
};
VALUE arg = (VALUE)&args;
rb_hash_modify(self);
return rb_ensure(rb_hash_update_call, arg, rb_hash_update_ensure, arg);
}
Updates values and/or adds entries to self; returns self.
Each argument other_hash in other_hashes must be a hash.
With no block given, for each successive entry key/new_value in each successive other_hash:
-
If
keyis inself, setsself[key] = new_value, whose position is unchanged:Exampleh0 = {foo: 0, bar: 1, baz: 2} h1 = {bar: 3, foo: -1} h0.update(h1) # => {foo: -1, bar: 3, baz: 2}
-
If
keyis not inself, adds the entry at the end ofself:Exampleh = {foo: 0, bar: 1, baz: 2} h.update({bam: 3, bah: 4}) # => {foo: 0, bar: 1, baz: 2, bam: 3, bah: 4}
With a block given, for each successive entry key/new_value in each successive other_hash:
-
If
keyis inself, fetchesold_valuefromself[key], calls the block withkey,old_value, andnew_value, and setsself[key] = new_value, whose position is unchanged :Exampleseason = {AB: 75, H: 20, HR: 3, SO: 17, W: 11, HBP: 3} today = {AB: 3, H: 1, W: 1} yesterday = {AB: 4, H: 2, HR: 1} season.update(yesterday, today) {|key, old_value, new_value| old_value + new_value } # => {AB: 82, H: 23, HR: 4, SO: 17, W: 12, HBP: 3}
-
If
keyis not inself, adds the entry at the end ofself:Exampleh = {foo: 0, bar: 1, baz: 2} h.update({bat: 3}) { fail 'Cannot happen' } # => {foo: 0, bar: 1, baz: 2, bat: 3}
Related: see Methods for Assigning.
See also
#transform_values!
#value?
#transform_values
#values
also in
4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0