像`self`这样引用实例的Ruby方法

ami*_*dfv 16 ruby oop

Ruby中是否有一个方法引用类的当前实例,self引用类本身的方式?

Jos*_*Lee 45

self总是指一个实例,但一个类本身就是一个实例Class.在某些情况下,self将参考这样的实例.

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
Run Code Online (Sandbox Code Playgroud)

输出:

Hello
#<Hello:0x7ffa68338190>
Hello
Run Code Online (Sandbox Code Playgroud)


Flo*_*aus 5

在一个实例中,类的方法self引用该实例.要在一个实例中获取该类,您可以调用它self.class.如果您self在类方法中调用,则会获得该类.在类方法中,您无法访问该类的任何实例.