开发者

Why does defining a method at the top level affect other user-defined classes?

开发者 https://www.devze.com 2023-04-13 03:00 出处:网络
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:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消