Skip to content

Instantly share code, notes, and snippets.

@trak3r
Created November 12, 2009 15:11
Show Gist options
  • Save trak3r/232964 to your computer and use it in GitHub Desktop.
Save trak3r/232964 to your computer and use it in GitHub Desktop.
class Array
def indifferent_intersection(other)
self.collect{|i| i.to_sym} & other.collect{|i| i.to_sym}
end
end
class Hash
def keyqual?(other)
return true if other.nil?
intersecting_keys = self.keys.indifferent_intersection(other.keys)
intersecting_keys.all? do |k|
self[k].to_s == other[k].to_s
end
end
end
require 'test_helper'
class HashKeyqualityTest < ActiveSupport::TestCase
test "graceful nil handling" do
a = {
# empty
}
b = nil
assert a.keyqual?(b)
end
test "integer and string values equate" do
a = {
:a => 1,
}
b = {
:a => '1',
}
assert a.keyqual?(b)
assert b.keyqual?(a)
end
test "symbol and string keys equate" do
a = {
:a => 1,
}
b = {
'a' => 2,
}
assert !a.keyqual?(b)
assert !b.keyqual?(a)
end
test "match on empties" do
a = {
:a => 1,
}
b = {
# empty
}
assert a.keyqual?(b)
assert b.keyqual?(a)
end
test "match on zero intersections" do
a = {
:a => 1,
}
b = {
:b => 2,
}
assert a.keyqual?(b)
assert b.keyqual?(a)
end
test "match on one intersection" do
a = {
:a => 1,
:b => 2,
}
b = {
:b => 2,
:c => 3,
}
assert a.keyqual?(b)
assert b.keyqual?(a)
end
test "match on two intersections" do
a = {
:a => 1,
:b => 2,
:c => 3,
}
b = {
:b => 2,
:c => 3,
:d => 4,
}
assert a.keyqual?(b)
assert b.keyqual?(a)
end
test "mis-match on one intersection" do
a = {
:a => 1,
:b => 2,
}
b = {
:b => 3,
:c => 4,
}
assert !a.keyqual?(b)
assert !b.keyqual?(a)
end
test "mis-match on two intersections" do
a = {
:a => 1,
:b => 2,
:c => 3,
}
b = {
:b => 3,
:c => 4,
}
assert !a.keyqual?(b)
assert !b.keyqual?(a)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment