在许多语言中,对象(例如类实例)内部都有一个 this
的概念。考虑这个通用的伪代码:
class Foo {
int x;
constructor() {
this.x = 10;
}
}
此处 this
提供从内部访问对象。它可以在许多方面发挥作用。
现在,我找不到如何从 Ruby 类内部访问 this
。我看到属性可以通过 @
前缀访问,方法可以通过它们的名称访问,但这些只是实例的一部分,而不是实例本身。所以问题是:我们如何从该对象内部访问完整的 Ruby 对象?
在ruby中,你应该使用self
而不是this
,是等价的。
现在,我们了解了实例和类方法之间的区别。
看例子:
class Person < ActiveRecord::Base
def self.class_method_example
return self
end
def instance_method_example
return self
end
end
在第一种情况下,我们可以将类与结果进行比较:
Person.class_method_example == Person # this returns true
在第二种情况下,我们只能使用 Person 实例调用该方法:
Person.first.instance_method_example == Person.first # this returns true
更新
在第二个示例中,我假设 ActiveRecord::Base
的扩展使用 first
方法