Ruby style guide by bbatsov建议不要使用self
。这是他的两个直接例子:
# bad
def ready?
if self.last_reviewed_at > self.last_updated_at
self.worker.update(self.content, self.options)
self.status = :in_progress
end
self.status == :verified
end
# good
def ready?
if last_reviewed_at > last_updated_at
worker.update(content, options)
self.status = :in_progress
end
status == :verified
end
他为什么提出这个建议?使用self
表示对象自身方法的引用可能会导致什么问题? (我刚刚目睹的唯一一个实例是在实例方法中调用私有方法时不要使用self)。
答案 0 :(得分:1)
Ruby在很大程度上是关于优雅,其中很大一部分是可读性。不必要的限定符是语法噪音,它会阻碍它。
该示例说明除了赋值情况之外的所有self
是如何不必要的,其中如果尚未限定,Ruby将创建名为status
的局部变量。通过使用self.status=
形式,Ruby很清楚您想在status=
上调用self
方法。