combine two maps in ruby

To combine two maps (hashes) in Ruby, we can use the merge method.

main.rb
map1 = { a: 1, b: 2 }
map2 = { c: 3, d: 4 }

combined_map = map1.merge(map2)

puts combined_map
# Output: { :a => 1, :b => 2, :c => 3, :d => 4 }
145 chars
8 lines

In the example above, map1 and map2 are two separate maps (hashes) with key value pairs. We merge them using the merge method and storing the result in a new variable called combined_map. The resulting map will have all the key-value pairs from both map1 and map2.

Note that if there are any duplicate keys, the value from the second map (map2) will be used. If you want to prioritize values from the first map (map1), you can use the merge! method instead.

related categories

gistlibby LogSnag