Answer
The answer is simple: visibility visibility.
def encrypt_password self.encrypted_password = encrypt(password) end
There is (or rather should be at runtime) something called password . In your case, this is an attribute from the database. But it can also be a local variable. If no such name is found, an error will be raised.
But you need to attach encrypted_password to self to explicitly indicate that you are going to update the instance attribute. Otherwise, a new local variable encrypted_password will be created. Obviously, this is not the effect you need.
Additional Information
Here is a small piece of code
class Foo attr_accessor :var def bar1 var = 4 puts var puts self.var end end f = Foo.new f.var = 3 f.bar1
Output
4 3
So, as we can see, var is assigned without the keyword self , and because of this, now there are two var names in the scope: a local variable and an instance attribute. The instance attribute is hidden by a local variable, so if you really want to access it, use self .
source share