Ruby - Merge Two Hashes

1. Introduction

Merging two hashes is a common operation in Ruby when you want to combine two sets of key-value pairs. This post will guide you through the process of merging two hashes in Ruby.

2. Program Steps

1. Create two separate hashes.

2. Use the merge method to combine them into a new hash.

3. Print the merged hash.

3. Code Program

# Creating two separate hashes
hash1 = {
  "name" => "Alice",
  "age" => 30,
  "city" => "New York"
}
hash2 = {
  "job" => "Engineer",
  "company" => "TechCorp",
  "city" => "Los Angeles"
}
# Merging the two hashes
merged_hash = hash1.merge(hash2)
# Printing the merged hash
puts merged_hash

Output:

{"name"=>"Alice", "age"=>30, "city"=>"Los Angeles", "job"=>"Engineer", "company"=>"TechCorp"}

Explanation:

1. We have two hashes named hash1 and hash2 with some key-value pairs.

2. The merge method is invoked on hash1 and hash2 is passed as an argument. This creates a new hash containing all the key-value pairs from both hash1 and hash2. If there are duplicate keys, the value from hash2 will overwrite the value from hash1.

3. The merged hash is then printed using the puts method, displaying the combined key-value pairs from both hashes.


Comments