We learned how to create a reader method in our lesson on making custom classes. Here’s a quick code recap:
class Cat
def initialize(name, age)
@name = name
@age = age
end
def name
@name
end
def age
@age
end
end
Now we can instantiate a new Cat
and read the age
and name
attributes:
> cat = Cat.new("Milo", 15)
> cat.name
=> "Milo"
> cat.age
=> 15
We probably won’t change our cat’s name, but we might want to change his age. Let’s try to do that:
> cat.age = 16
undefined method `age=' for #<Cat:0x007fa313a9ca78 @name="Milo", @age=15>
We got an error because we don’t have a writer method for the age
attribute. While a reader method lets us read an attribute of a Ruby object, a writer method lets us write an attribute. Let’s add a writer method to the Cat
class:
class Cat
...
def age=(age)
@age = age
end
end
Here we create a new method called age=
with the parameter age
. Our method then sets the value of @age
to the value we pass into the parameter.
We can now do the following:
> cat = Cat.new("Milo", 15)
> cat.name()
=> "Milo"
> cat.age
=> 15
> cat.age = 16
=> 16
> cat.age
=> 16
As you can see, Ruby lets us call this method in the same way we'd assign a variable, including adding spaces before and after the =
sign. Though we certainly could, we don't have to do this:
> cat.age=(16)
This is another example of how Ruby provides syntactic sugar to make code easier to read and write.
Just because we can add writer methods doesn’t mean we should. It makes sense to add a writer method to age
because that value will change from time to time. However, you might not want to make it so easy to change the name
value. Whenever you add reader and writer methods to your application, it’s important to think carefully about whether you need them. In certain situations, they can be potential security risks; you wouldn’t want to have read/write access on a Person
’s bank account number, for example.
Adding reader and writer methods to a Ruby class is easy, but it can get irritating when an object instance has many attributes. Soon we’ll learn a way to make writing reader and writer methods even easier. For now, practice writing your own reader and writer methods. As always, make sure you test all of your methods, including reader and writer methods. Here are some sample tests to get you started:
describe(Cat) do
describe("#name") do
it("returns a cat's name") do
cat = Cat.new("Milo", 15)
expect(cat.name()).to(eq("Milo"))
end
end
describe("#name=") do
it("changes a cat's name") do
cat = Cat.new("Milo", 15)
cat.name = "Kiki"
expect(cat.name()).to(eq("Kiki"))
end
end
end
class Cat
...
def age=(age)
@age = age
end
end
Lesson 11 of 22
Last updated August 7, 2022