find the intersection of two maps in ruby

To find the intersection of two maps (also known as hashes), we can use the select method in combination with the keys method. The select method returns a new hash containing key-value pairs for which the block returns true. By selecting only the keys that exist in both maps, we can find the intersection.

Here's an example implementation:

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

intersection = map1.select { |key, _| map2.keys.include?(key) }

puts intersection # Output: { b: 2, c: 3 }
165 chars
7 lines

In this example, we define two maps map1 and map2. We then use the select method on map1, checking if each key is present in map2 using the keys method. The result is a new hash containing only the key-value pairs where the key is present in both maps.

The resulting intersection map in the above example contains { b: 2, c: 3 }, since those are the keys present in both map1 and map2.

related categories

gistlibby LogSnag