gpt4 book ai didi

ruby-on-rails - 如何在 Rails 中使用 "self"关键字

转载 作者:数据小太阳 更新时间:2023-10-29 07:24:04 26 4
gpt4 key购买 nike

关于Rails中的关键字self,我知道关键字指的是类本身的一个实例。例如,在 self.encrypted_pa​​ssword 中。

我不太明白为什么在右侧作为参数传递的属性 password 也没有以 self 关键字为前缀?

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 关键字?

最佳答案

回答

答案很简单:范围可见性。

def encrypt_password
self.encrypted_password = encrypt(password)
end

有(或者更确切地说,应该在运行时有)东西叫做password。在您的情况下,它是数据库中的一个属性。但它也可以是局部变量。如果找不到这样的名称,则会引发错误。

但您必须encrypted_pa​​ssword 前加上self 以明确声明您将更新实例属性。否则,将创建新的局部变量 encrypted_pa​​ssword。显然,不是你想要的效果。

更多解释

这是一小段代码

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

关于ruby-on-rails - 如何在 Rails 中使用 "self"关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8844703/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com