← Back to blog

How to Compare Two Ruby Hashes and Find the Difference

· Lachlan Young

You have two hashes and you need to know how they differ. Maybe one is the expected result in a test and the other is what your code produced. Maybe one is yesterday’s API response and the other is today’s. Either way, “are these the same, and if not, what changed?” is a question Ruby can answer in several ways. Here are the options, from simplest to most thorough, plus the traps that make a “correct” comparison lie to you.

Equality: are they the same at all?

The first question is just whether the two hashes are equal. Ruby’s == compares hashes by content, not order:

a = { name: "Alice", role: "admin" }
b = { role: "admin", name: "Alice" }

a == b   # => true   (order does not matter for ==)

This tells you whether they differ, but not how. For small hashes that might be all you need. For anything larger, you want the specific differences.

Two equality traps

== is looser than most people expect, and stricter in a different way than most people expect.

{ a: 1 } == { a: 1.0 }        # => true   (1 == 1.0)
{ a: 1 }.eql?({ a: 1.0 })     # => false  (eql? checks type too)
{ "id" => 1 } == { id: 1 }    # => false  (String key vs Symbol key)

The first one means == will happily call an integer and a float “the same”, which can hide a real change when a serializer starts emitting 1.0 instead of 1. If the type matters, use eql?. The third one is the classic reason two hashes that look identical in a failing test are not equal: one has string keys (from JSON.parse or params) and the other has symbol keys. inspect output makes that easy to miss when you are skimming.

Is one hash contained in the other?

Often you do not need full equality. You want to know whether the actual result contains at least what you expected. Hash defines subset comparison operators for this:

expected = { id: 1, name: "Alice" }
actual   = { id: 1, name: "Alice", role: "admin" }

expected <= actual   # => true   (every pair in expected is in actual)
actual <= expected   # => false
expected < actual    # => true   (a strict subset)

This is a clean way to assert “the response includes these fields” without caring about extras such as created_at. It compares keys and values together, so a matching key with a different value still returns false.

Finding changed and missing keys with plain Ruby

Ruby’s Hash and Array give you enough to compute differences by hand.

Which keys exist in one but not the other

expected = { id: 1, name: "Alice", role: "admin" }
actual   = { id: 1, name: "Alice", plan: "pro" }

expected.keys - actual.keys   # => [:role]   (missing from actual)
actual.keys - expected.keys   # => [:plan]   (extra in actual)

Which shared keys have different values

shared = expected.keys & actual.keys
changed = shared.reject { |k| expected[k] == actual[k] }
changed.map { |k| [k, expected[k], actual[k]] }
# => []  (in this case the shared keys all match)

The pair-subtraction shortcut

Converting each hash to an array of [key, value] pairs lets you subtract them, which catches both missing keys and changed values in one move:

a = { id: 1, name: "A", role: "admin" }
b = { id: 1, name: "B", plan: "pro" }

(a.to_a - b.to_a).to_h   # => {:name=>"A", :role=>"admin"}  (only in a)
(b.to_a - a.to_a).to_h   # => {:name=>"B", :plan=>"pro"}    (only in b)

Notice :name shows up on both sides, which is how you know the value changed rather than the key being absent. It is a quick console trick, though it does not tell you which of the two situations you are in without a second look.

A one-shot difference of two flat hashes

Combining the ideas, you can build a small diff:

def hash_diff(a, b)
  (a.keys | b.keys).each_with_object({}) do |key, diff|
    next if a[key] == b[key]
    diff[key] = { expected: a[key], actual: b[key] }
  end
end

hash_diff(expected, actual)
# => {:role=>{:expected=>"admin", :actual=>nil},
#     :plan=>{:expected=>nil, :actual=>"pro"}}

This works well for flat hashes. It is worth keeping in a test helper. It has one flaw worth knowing about: because it reads a[key], a key that is present with a nil value looks identical to a key that is missing. If that distinction matters (and in API payloads it often does), check a.key?(key) as well.

A note for Rails users: older versions of ActiveSupport had a Hash#diff method, but it was deprecated and then removed (in Rails 6.1, as far as I know), so do not rely on it in a modern app.

The hard case: nested hashes

Real data is rarely flat. Once you have hashes inside hashes inside arrays, a shallow == per key stops being enough, because two nested hashes are only == if everything inside them matches, and when they do not, plain Ruby just tells you the whole subtree differs without saying where.

a = { user: { name: "Alice", address: { city: "Melbourne" } } }
b = { user: { name: "Alice", address: { city: "Sydney" } } }

a == b   # => false, but where?

You can write a recursive diff that walks both structures in parallel and reports the path to each difference. This version tracks added keys, removed keys and changed values, and compares arrays by index:

def deep_diff(a, b, path = [])
  return [] if a == b

  if a.is_a?(Hash) && b.is_a?(Hash)
    (a.keys | b.keys).flat_map do |key|
      if !a.key?(key)
        [{ path: path + [key], change: :added, actual: b[key] }]
      elsif !b.key?(key)
        [{ path: path + [key], change: :removed, expected: a[key] }]
      else
        deep_diff(a[key], b[key], path + [key])
      end
    end
  elsif a.is_a?(Array) && b.is_a?(Array)
    (0...[a.size, b.size].max).flat_map do |i|
      deep_diff(a[i], b[i], path + [i])
    end
  else
    [{ path: path, change: :changed, expected: a, actual: b }]
  end
end

a = { user: { tags: ["a", "b"], address: { city: "Melbourne" } }, id: 1 }
b = { user: { tags: ["a", "c", "d"], address: { city: "Sydney" } }, id: "1", plan: "pro" }

deep_diff(a, b).each { |d| puts d.inspect }
# {:path=>[:user, :tags, 1], :change=>:changed, :expected=>"b", :actual=>"c"}
# {:path=>[:user, :tags, 2], :change=>:changed, :expected=>nil, :actual=>"d"}
# {:path=>[:user, :address, :city], :change=>:changed, :expected=>"Melbourne", :actual=>"Sydney"}
# {:path=>[:id], :change=>:changed, :expected=>1, :actual=>"1"}
# {:path=>[:plan], :change=>:added, :actual=>"pro"}

That is a reasonable starting point, and the path array can be fed straight into dig to fetch the value on either side. It is still a rough tool, though. Comparing arrays by index means that inserting one element at the front reports every later element as changed. If your arrays are really unordered collections of records, you need to match elements by an id first, which is a different problem entirely (see the post on comparing arrays of hashes). And it treats 1 versus "1" as a plain value change, which is correct but gives you no hint that it is a type problem.

For a one-off debugging session, extending that code is slower than the problem you are trying to solve.

The fast path: a visual side-by-side diff

When you just need to see the difference, especially for nested or large hashes, a visual diff is the quickest route. RubyHash is built for exactly this. Paste both hashes, in Ruby syntax straight from a console or test, and it:

For the nested example above, you would see the diff drill straight down to user.address.city changing from Melbourne to Sydney, with everything else greyed out as unchanged. No recursive diff code, no mental bookkeeping of brace levels.

It runs in your browser and sends nothing to a server, so it is safe to use with real data from a failing test.

Which approach should you use?

The right tool depends on whether you need the comparison in code (write the helper) or you need to see it now (use the visual diff). Most debugging sessions are the second kind, which is exactly why the tool exists.


Comparing Ruby hashes and need to spot the difference fast? Try RubyHash, paste your two hashes for a clean, side-by-side diff.

Enjoyed this post?

Subscribe to get notified when we publish more Ruby and Rails content.