Skip to content

Instantly share code, notes, and snippets.

@alexrothenberg
Forked from drewblas/ruby_quiz1.rb
Last active December 13, 2015 17:09
Show Gist options
  • Save alexrothenberg/4945789 to your computer and use it in GitHub Desktop.
Save alexrothenberg/4945789 to your computer and use it in GitHub Desktop.
# =============================
# Test case showing what we expect to happen
a1 = 'z'
b1 = 'z'
a = [a1]
b = [b1]
# array '-' https://github.com/ruby/ruby/blob/trunk/array.c#L3806
# It compares elements using their #hash and #eql? methods for efficiency.
# same hashes mean they will be subtracted
a.map(&:hash) # => [1716651113021123031]
b.map(&:hash) # => [1716651113021123031]
a1 == b1 # true
a1.eql? b1 # true
a1.equal? b1 # false different object_ids, as expected
a.eql? b # true
a - b # = []
b - a # = []
#EVERYTHING IS GOOD HERE. DIFFERENT OBJECT_IDS BUT EQUAL OBJECTS SUBTRACT OUT OF ARRAY
# =============================
# Simple class that should act the same as above
class MyObject
attr_accessor :str
def initialize(str)
@str = str
end
def eql?(other)
@str.eql? other.str
end
def ==(other)
@str == other.str
end
end
# =============================
# Test case that is messed up!
object1 = MyObject.new('z')
object2 = MyObject.new('z')
a = [object1]
b = [object2]
# different hashes mean they will not be subtracted
a.map(&:hash) # => [-3103761982373525360]
b.map(&:hash) # => [-1675791735293861944]
object1 == object2 # true
object1.eql? object2 # true
object1.equal? object2 # false different object_ids, as expected
a.eql? b # true
a - b # = [object1]
b - a # = [object2]
# WHY ARE THESE NOT EMPTY?!?!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment