Set Operations on Hashes
suggest change- Intersection of hashes
Return the shared keys whose values are equal:
hash1 = { a: 1, b: 2 }
hash2 = { b: 2, c: 3 }
hash1.select { |k, v| hash2.include?(k) && hash2[k] == v } # => { b: 2 }
- Union (merge) of hashes
Keys in a hash are unique. If a key is in both hashes, merge keeps the value from the argument, not from the receiver:
hash1 = { a: 1, b: 2 }
hash2 = { b: 4, c: 3 }
hash1.merge(hash2) # => { a: 1, b: 4, c: 3 }
hash2.merge(hash1) # => { b: 2, c: 3, a: 1 }
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents