Created
February 13, 2013 16:14
-
-
Save drewblas/4945697 to your computer and use it in GitHub Desktop.
Ruby Quiz
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ============================= | |
# Test case showing what we expect to happen | |
a1 = 'z' | |
b1 = 'z' | |
a = [a1] | |
b = [b1] | |
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] | |
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?!?! |
elight
commented
Feb 13, 2013
So Array#- appears to be hashing the contents as part of its impl?
1.9.3p125 :018 > object1 = MyObject.new('z')
=> #<MyObject:0x007fd23a6d7540 @str="z">
1.9.3p125 :019 > object2 = MyObject.new('z')
=> #<MyObject:0x007fd23a6d9b38 @str="z">
1.9.3p125 :020 > a = [object1]
=> [#<MyObject:0x007fd23a6d7540 @str="z">]
1.9.3p125 :021 > b = [object2]
=> [#<MyObject:0x007fd23a6d9b38 @str="z">]
1.9.3p125 :022 > a.hash
=> -2390116867273082033
1.9.3p125 :023 > b.hash
=> 19342702949669274
1.9.3p125 :024 >
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment