Method: Immutable::Hash#merge

Defined in:
lib/immutable/hash.rb

#merge(other) {|key, my_value, other_value| ... } ⇒ Hash

Return a new Hash containing all the key/value pairs from this Hash and other. If no block is provided, the value for entries with colliding keys will be that from other. Otherwise, the value for each duplicate key is determined by calling the block.

other can be an Immutable::Hash, a built-in Ruby Hash, or any Enumerable object which yields ‘[key, value]` pairs.

Examples:

h1 = Immutable::Hash["A" => 1, "B" => 2, "C" => 3]
h2 = Immutable::Hash["C" => 70, "D" => 80]
h1.merge(h2)
# => Immutable::Hash["C" => 70, "A" => 1, "D" => 80, "B" => 2]
h1.merge(h2) { |key, v1, v2| v1 + v2 }
# => Immutable::Hash["C" => 73, "A" => 1, "D" => 80, "B" => 2]

Parameters:

Yield Parameters:

  • key (Object)

    The key which was present in both collections

  • my_value (Object)

    The associated value from this Hash

  • other_value (Object)

    The associated value from the other collection

Yield Returns:

  • (Object)

    The value to associate this key with in the new Hash

Returns:



479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
# File 'lib/immutable/hash.rb', line 479

def merge(other)
  trie = if block_given?
    other.reduce(@trie) do |trie, (key, value)|
      if entry = trie.get(key)
        trie.put(key, yield(key, entry[1], value))
      else
        trie.put(key, value)
      end
    end
  else
    @trie.bulk_put(other)
  end

  derive_new_hash(trie)
end