How to replace the contents of one hash with another in Ruby

Overview

The contents of a certain hash can be replaced in Ruby by using the replace() method. It replaces the entire contents of a hash with the contents of another hash.

Syntax

hash.replace(another_hash)

Parameters

hash: This is the hash whose contents we want to replace with another hash.

another_hash: This is the hash that will replace the contents of the hash hash.

Return value

The hash is still returned but its original contents are replaced by contents of hash another_hash.

Example

# create hashes
h1 = {one: 1, two: 2, three: 3}
h2 = {name: "okwudili", stack: "ruby"}
h3 = {"foo": 0, "bar": 1}
h4 = {M:"Mango", A: "Apple", B: "Banana"}
# replace hash contents
# and print results
puts h1.replace(h2)
puts h2.replace(h3)
puts h3.replace(h4)
puts h4.replace(h1)

Explanation

  • Lines 2 to 5: We create some hashes.
  • Lines 9 to 12: We use the replace() method to replace hash contents with another.

Free Resources