If I define a top level method like this:
def inspect(x)
# do something useful...
end
Then calling #inspect
on a user-defined class stops working:
class Foo; end
p Foo.new # `inspect': wrong number of arguments (0 for 1) (ArgumentError)
However, it keeps working for classes like NilClass
and String
:
p nil # prints 'nil'
p "test" # prints '"test"'
I thought that one explanation for this behaviour could be that top-level execution may be in the Object
class itself, but it turns out that it's in an instance of Object
called main
. Doesn't this 开发者_如何学Gomean that methods defined here shouldn't affect other classes?
main
is a special place. Any methods defined there are defined as private instance methods of Object. This is so you can define pseudo-functions that can be called in any context without an explicit receiver.
精彩评论