Contents

Roo

Hash.merge()

There are two merge() methods.

First form

hash.merge(other as Hash) as Hash

Returns a new Hash formed by merging this hash with the passed other hash.

Parameters

  • other. Hash object. The hash with which to merge with. The value for entries with duplicate keys will be that of the other hash

Returns

  • A new Hash object. The original hash is unaltered

Example

var h1 = {"a" => 100, "b" => 200}
var h2 = {"b" => 254, "c" => 300}
var h3 = h1.merge(h2)

print(h1) # => {"a" => 100, "b" => 200}
print(h2) # =>{"b" => 254, "c" => 300}
print(h3) # => {"a"=>100, "b"=>254, "c"=>300}

Second form

hash.merge(other as Hash, func as Function) as Hash

Returns a new Hash formed by merging this hash with the passed other hash. The value for entries with duplicate keys will be determined by the return value of func.

Parameters

  • other. Hash object. The hash with which to merge with
  • func. A reference to a function. This function must take 3 parameters: key, old_value and other_value. key is the current key, other_value is the corresponding value for this key in this hash and new_value is the corresponding value for this key in the other hash.

Returns

  • A new Hash object. The original hash is unaltered

Example

function custom_merge(key, old_val, other_val) {
    # Return the difference between the two values when a
    # duplicate key is encountered.
    return other_val - old_val
}

var h1 = { "a" => 100, "b" => 200 }
var h2 = { "b" => 254, "c" => 300 }
var h3 = h1.merge(h2, custom_merge) # => {"a"=>100, "b"=>54,  "c"=>300}