Q:

Comparing two similar hashes in ruby

I'm using ruby 1.8.7 and I need to compare two hashes that I have, which are essentially the attributes of a model.  Hash A is smaller than Hash B, and Hash B has all of the attributes of hash A, plus some extra attributes I don't care about.  My overarching goal is to see if the elements of A are the same as the respective elements of B.  So for example
@hash_a = {:cat => 'Bubby', :dog => 'Gizmo'}  
@hash_b = {:cat => 'Bubby', :dog => 'Gizmo', :lion => 'Simba'}  
@hash_a == @hash_b
#=> true

Now it gets a little bit more complicated than that because the fields don't match up completely, even though they referance the same piece of information
@hash_a = {:cats_name => 'Bubby', :dog => 'Gizmo'}  
@hash_b = {:cat => 'Bubby', :dog => 'Gizmo', :lion => 'Simba'}  
@hash_a == @hash_b
#=> true

What I'm working on is a process that compares two matching items, updates it if the fields have changed, and only if they changed.  Or creates a new item if it cannot find a matching item.  Changing the names of the hash itself is not an option.  Currently I'm just comparing each field in a private method to see if they are equal.
return hash_a[:cat] == hash_b[:cats_name] && hash_a[:dog] == hash_b[:dog] 

I feel like there has to be a better way, I'm looking for something faster and more elegant than this.

A:

If you convert the hashes to an array, you can compare them like this.
@hash_a.to_a == (@hash_a.to_a & @hash_b.to_a)

You could also hide this code behind a method in the hash class if you wanted:
class Hash
  def diff_equal(other)
    to_a == (to_a & other.to_a)
  end
end

Then use it like @hash_a.diff_equal(@hash_b). If you chose that path, you might want to check that other is a hash or responds to the to_a method.

