Skip to content

Instantly share code, notes, and snippets.

@drewblas
Created February 13, 2013 16:14
Show Gist options
  • Save drewblas/4945697 to your computer and use it in GitHub Desktop.
Save drewblas/4945697 to your computer and use it in GitHub Desktop.
Ruby Quiz
# =============================
# 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
Copy link

elight commented Feb 13, 2013

1.9.3p125 :019 > [BasicObject.new] - [BasicObject.new]
NoMethodError: undefined method `hash' for #<BasicObject:0x007f985af62e68>
    from (irb):19:in `-'
    from (irb):19
    from /Users/light/.rvm/rubies/ruby-1.9.3-p125/bin/irb:16:in `<main>'
1.9.3p125 :020 > a.hash
TypeError: can't convert Array into Integer
    from (irb):20:in `hash'
    from (irb):20
    from /Users/light/.rvm/rubies/ruby-1.9.3-p125/bin/irb:16:in `<main>'
1.9.3p125 :021 > b.hash
TypeError: can't convert Array into Integer
    from (irb):21:in `hash'
    from (irb):21
    from /Users/light/.rvm/rubies/ruby-1.9.3-p125/bin/irb:16:in `<main>'
1.9.3p125 :022 > [42].hash
 => -3881995855182782207 
1.9.3p125 :023 > [42].hash
 => -3881995855182782207 
1.9.3p125 :024 > 

@elight
Copy link

elight commented Feb 13, 2013

So Array#- appears to be hashing the contents as part of its impl?

@elight
Copy link

elight commented Feb 13, 2013

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