如何使用“自我"? Rails中的关键字 [英] How to use the "self" keyword in Rails
问题描述
关于Rails中的关键字self
,我知道该关键字引用了类本身的一个实例.例如,在self.encrypted_password
中.
Regarding the keyword self
in Rails, I know that the keyword refers to an instance of the class itself. For example, in self.encrypted_password
.
我几乎不知道为什么在右侧作为参数传递的属性password
也没有以self
关键字作为前缀吗?
I have less of an idea why the attribute password
, passed as an parameter on the right hand side, isn't prefixed with the self
keyword too?
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :name, :email, :password, :password_confirmation
validates :password, :presence => true,
:confirmation => true,
:length => { :within => 6..40 }
before_save :encrypt_password
private
def encrypt_password
self.encrypted_password = encrypt(password)
end
def encrypt(string)
string # Only a temporary implementation!
end
end
有人可以解释何时使用或不使用self
关键字吗?
Can someone explain when to use, or not use, the self
keyword?
推荐答案
答案
答案很简单:范围可见性.
Answer
The answer is simple: scope visibility.
def encrypt_password
self.encrypted_password = encrypt(password)
end
有(或者应该在运行时应该有)称为password
的东西.在您的情况下,它是数据库中的一个属性.但它也可以是局部变量.如果找不到该名称,则会引发错误.
There is (or, rather, there should be at runtime) something called password
. In your case, it's an attribute from the database. But it also can be a local variable. If such name isn't found, error will be raised.
但是您必须在encrypted_password
之前加上self
前缀,以明确声明您将要更新实例属性.否则,将创建新的局部变量encrypted_password
.显然,这不是您想要的效果.
But you have to prefix encrypted_password
with self
to explicitly state that you're going to update instance attribute. Otherwise, new local variable encrypted_password
will be created. Obviously, not the effect you wanted.
这是一小段代码
class Foo
attr_accessor :var
def bar1
var = 4
puts var
puts self.var
end
end
f = Foo.new
f.var = 3
f.bar1
输出
4
3
因此,如我们所见,var
被分配为没有self
关键字,因此,在作用域中现在有两个名称var
:局部变量和实例属性.实例属性被局部变量隐藏,因此,如果您确实要访问它,请使用self
.
So, as we can see, var
is assigned without self
keyword and, because of this, now there are two names var
in the scope: local variable and instance attribute. Instance attribute is hidden by local variable, so if you really want to access it, use self
.
这篇关于如何使用“自我"? Rails中的关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!