Definition of method in top level

前端 未结 2 1221
野的像风
野的像风 2021-01-21 19:02

I\'m wondering about definition of method in top level.

puts RUBY_VERSION #=> 2.1.5
def greet
  \"hello, world\"
end
class Object
    greet #=> \"hello, wo         


        
2条回答
  •  有刺的猬
    2021-01-21 19:52

    Why does greet act like private class method?

    It doesn't. It acts like a private instance method. (In fact, there are no class methods in Ruby, only instance methods. The question is not whether a method is an instance method or a class method, rather it's what class the instance method is defined in.)

    Methods defined at the top-level become private instance methods of Object.

    # case 1
    Object.private_methods(false).grep /greet/ #=> []
    # case 2
    Object.private_instance_methods(false).grep /greet/ #=> [:greet]
    # case 3
    Object.private_methods(true).grep /greet/ #=> [:greet]
    

    In case 3, I found that greet is a private class method.

    Like I said above: there are no class methods in Ruby.

    greet is a private instance method of Object. Object is an instance of Class, Class is a subclass of Module, Module is a subclass of Object, ergo Object is an instance of Object i.e. itself.

    Put another way: methods defined in Object are available for all objects. Classes are objects, too, ergo methods defined in Object are available for all classes, including Object.

    But I'm wondering which class owns greet as a private class method.

    None. There are no class methods in Ruby. greet is a private instance method of Object.

    Object inherits itself?

    No. Object is an instance of itself.

    Question #1

    Does definition of method mean adding some methods in Object as private instance method.
    Is this correct ?

    Methods defined at the top-level become private instance methods of Object.

    Question #2

    Object is an instance of Class. So, Object owns private class methods. These methods as private instance methods in Class.
    Is this correct ?

    I cannot parse your question, sorry.

    However, there are no private instance methods of Class in your examples. The only method in your example is greet, which is a private instance method of Object, not Class.

    If you want to know who owns a method, you can just ask Ruby:

    method(:greet).owner
    # => Object
    

    Question #3

    depends on question #1 and #2. Class inherits Object. So, Class owns >greet as private class method and private instance method. Is this correct ?

    No. There are no class methods in Ruby, only instance methods. And greet is not owned by Class, it is a private instance method of Object:

    method(:greet).owner
    # => Object
    

提交回复
热议问题