Ruby method like `self` that refers to instance

前端 未结 5 365
迷失自我
迷失自我 2021-02-02 13:50

Is there a method in Ruby that refers to the current instance of a class, in the way that self refers to the class itself?

5条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-02 14:12

    self always refers to an instance, but a class is itself an instance of Class. In certain contexts self will refer to such an instance.

    class Hello
      # We are inside the body of the class, so `self`
      # refers to the current instance of `Class`
      p self
    
      def foo
        # We are inside an instance method, so `self`
        # refers to the current instance of `Hello`
        return self
      end
    
      # This defines a class method, since `self` refers to `Hello`
      def self.bar
        return self
      end
    end
    
    h = Hello.new
    p h.foo
    p Hello.bar
    

    Output:

    Hello
    #
    Hello
    

提交回复
热议问题