何时在 Ruby 方法中使用 `self.foo` 而不是 `foo`
这不是 Rails 特有的 - 我只是使用 Rails 作为示例。
我在 Rails 中有一个模型:(
class Item < ActiveRecord::Base
def hello
puts "Hello, #{self.name}"
end
end
假设 Item
模型(类)有一个名为 name
的方法。)什么时候需要使用 self.name
什么时候可以只使用name
(例如,#{name}
)?
This is not specific for Rails - I am just using Rails as an example.
I have a model in Rails:
class Item < ActiveRecord::Base
def hello
puts "Hello, #{self.name}"
end
end
(Let's assume that the Item
model (class) has a method called name
.) When do I need to use self.name
and when can I just use name
(e.g., #{name}
)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
调用方法时更喜欢省略
self.
是惯用的做法;通常不需要它。调用 setter 方法时必须使用
self.foo = xxx
,而不是foo = xxx
,以便 Ruby 意识到您并不是在尝试创建新的局部变量。do_something
,则必须使用self.do_something
来调用方法,因为do_something
最终会读取变量。你不能使用
self.foo(.. .)
调用私有方法;您必须只调用foo(...)
。It is idiomatic to prefer to omit
self.
when invoking methods; it is generally never needed.You must use
self.foo = xxx
when calling a setter method, instead offoo = xxx
, so that Ruby realizes that you are not trying create a new local variable.do_something
with the same name as a method, you must useself.do_something
to invoke the method, as justdo_something
will end up reading the variable.You cannot use
self.foo(...)
to call a private method; you must instead call justfoo(...)
.如果省略
self
Ruby 将首先查找具有该名称的局部变量,然后查找实例方法。写成self.
并不符合习惯用法。无论如何,您都必须在赋值时编写self.something = value
。请注意,调用私有方法时不能使用 self(受保护的方法没有问题):
If you omit
self
Ruby will first look for local variables with that name, then for an instance method. It's not idiomatic to writeself.
. In any case, you have to writeself.something = value
on assignations.Note that you cannot use
self
when calling private methods (no problem with protected methods):遵循本教程,您不需要使用self指针。但我认为 this (或在我们的例子中 self)指针用于解决名称冲突。实际上,
@name
和self.name
是相同的语句(如果您的类没有name
方法)。例如:尝试运行此代码,您会看到 =)
Following this tutorial, you have no need to use self pointer. But i think this (or self in our case) pointers are used to resolve name conflicts. Actually,
@name
andself.name
are the same statements (if there is noname
method for your class). E.g.:Try running this code and you'll see =)