Attribute Writers
Learn how to set attribute information
We'll cover the following
Setting attribute information
Imagine that a person not only needs a name but also a password. However, let’s also imagine that, at the time of the creation of a new person
instance, this password is not yet known.
Instead, we want to be able to tell the person
object about its email password later.
We can do this like so:
class Persondef initialize(name)@name = nameenddef name@nameenddef password=(password)@password = passwordendend
As we can see, the password=
method does nothing else but take a single argument (called password
) and assign the value of this local variable to the @password
instance variable.
Attribute writers called on an object
This method’s structure looks exactly the same as the structure of the initialize
method. This is true, except that initialize
is called behind the scenes whenever we call new
on the class. Our new password=
method needs to be explicitly called on the object itself once it’s been created.
Again, because this kind of method is used so often, there’s another name for it: it’s an attribute writer.
Now, we can use the attribute writer as shown:
person = Person.new("Ada")person.password=("super secret")p person
If we execute this, we can see that after calling person.password=("super secret")
, the object now has an instance variable defined. That is, the person now knows their password too.
Remember: An attribute writer allows us to set an instance variable.
That method call might look a little strange.
Syntax sugar for attribute writers
Just like Ruby adds syntax sugar for the assignment operator, =
, it does so for attribute writers too. In fact, exactly the same syntax works for attribute writers, that is, methods that end with an equals sign (=
).
So, we can also write this instead:
puts person = Person.new("Ada")puts person.password = "super secret"
This reads far better.
Remember that when running our code, Ruby internally translates the line person.password = "something"
to person.password=("something")
. This simply calls the password=
method, passing the value on the right hand side as an argument. It’s just another method.