Ruby self in layman terms?

前端 未结 3 536
梦毁少年i
梦毁少年i 2021-01-06 07:45

When is Ruby self refering to the Object and when is self refering to the Ruby class? Explanations with examples would be great. Not getting my head around this.

相关标签:
3条回答
  • 2021-01-06 08:23

    Classes are actually objects themselves. Lets say that I have a class Person, this is actually an instance of Class. So you can have self refer to an instance of Article, or you can have self refer to the instance of the class, Article.

    In the most simple example I can think of:

    class Person
      def initialize
        p "Info about Person Instance"
        p self
        p self.class
      end
    
      p "Info about Person Class"
      p self
      p self.class
    end
    
    
    person = Person.new
    

    It prints:

    "Info about Person Class"
    Person
    Class
    "Info about Person Instance"
    #<Person:0x0000010086cf58>
    Person
    

    To read more about about self, I highly recommend read this.

    0 讨论(0)
  • 2021-01-06 08:28

    My understanding is

    • In environments where you are defining class methods or module_functions, self refers to the class/module.
    • In environments where you are defining instance methods, self refers to the instance.

    For example,

    class A
      def method1
        self # => instance of A
      end
      def self.method2
        self # => class A
      endu
      def A.method3
        self # => class A
      end
    end
    
    class << A
      def method4
        self # => class A
      end
    end
    
    module B
      module_function
      def method5
        self # => module B
      end
    end
    

    Exceptions are that instance_eval, instance_exec alter self to the receiver.

    0 讨论(0)
  • 2021-01-06 08:45

    I could try to explain it myself, but I think Yehuda Katz does a better job than I would do:

    Metaprogramming in Ruby: It’s All About the Self

    0 讨论(0)
提交回复
热议问题