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)
在一个实例中,类的方法self引用该实例.要在一个实例中获取该类,您可以调用它self.class.如果您self在类方法中调用,则会获得该类.在类方法中,您无法访问该类的任何实例.