Ruby Language Set Operations on Hashes


Example

  • Intersection of Hashes

    To get the intersection of two hashes, return the shared keys the values of which 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 occurs in both hashes which are to be merged, the one from the hash that merge is called on is overwritten:

    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 }