-
-
Save avdi/2919483 to your computer and use it in GitHub Desktop.
class Foo | |
end | |
Foo.object_id # => 34581480 | |
f = Foo.new # => #<Foo:0x000000041f53c0> | |
f.class.object_id # => 34581480 | |
# This just prevents the "const redefined" warning | |
Object.send(:remove_const, :Foo) | |
# "Reload" class Foo | |
class Foo | |
end | |
Foo.object_id # => 34580180 | |
f.class.object_id # => 34581480 | |
f.is_a?(Foo) # => false | |
f.class == Foo # => false | |
f.class.name == "Foo" # => true |
Yes, it is. But surprising to newbs. This was born out of an OoR mailing list discussion.
It's an interesting point, I hadn't thought about this until this gist. Thanks for sharing anyway :)
It should not be surprising to newbs because the code specifically instructed ruby to remove the constant Foo.
Any other behaviour would be just as surprising, because you would then see that the constant would still exist, despite the code specifically telling ruby to remove that constant before.
If you would want that behaviour different, by treating class Foo the same, then you would have to disallow remove_const, because remove_const could no longer change ANY namespace (classes and modules are constants just as any other upcased first character)
@shevegen, Avdi is saying that actual newbs are actually surprised when they first encounter this behavior. Telling someone that they shouldn't be surprised by something that has surprised them is, in effect, a "well, actually".
The fundamental source of the surprise, as you point out, is remove_const. (Or, as I like to think of it, Ruby providing a concrete example of [the first half of] the adage "constants aren't, variables don't.") In many other languages, there's no equivalent -- once a reference is in the symbol table, it's there to stay.
Isn't this an expected behaviour? The second
Foo
has a different object id (lines 4, 17), butf
keeps being an instance of the firstFoo
definition. So, obviously, lines 20 and 21 fail, but line 21 still passes.Looks right to me.