如何在rails中使用self关键字

Sar*_*wan 4 ruby oop ruby-on-rails

关于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
Run Code Online (Sandbox Code Playgroud)

Ser*_*sev 8

回答

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

def encrypt_password
  self.encrypted_password = encrypt(password)
end
Run Code Online (Sandbox Code Playgroud)

有(或者更确切地说,应该在运行时)调用的东西password.在您的情况下,它是数据库中的属性.但它也可以是局部变量.如果找不到此名称,将引发错误.

但你必须前缀encrypted_passwordself明确指出你要更新实例属性.否则,encrypted_password将创建新的局部变量.显然,不是你想要的效果.

更多解释

这里有一小段代码

class Foo
  attr_accessor :var

  def bar1
    var = 4
    puts var
    puts self.var
  end
end

f = Foo.new
f.var = 3
f.bar1
Run Code Online (Sandbox Code Playgroud)

产量

4
3
Run Code Online (Sandbox Code Playgroud)

因此,正如我们所看到的,var分配时没有self关键字,因此,现在var范围内有两个名称:局部变量和实例属性.Instance属性由局部变量隐藏,因此如果您确实想要访问它,请使用self.