This article is about attribute accessors (attr_accessor) in Ruby.
If you’re in a hurry, scroll down.
Because I would like to start by explaining:
Why we use attribute accessors!
Let’s say that you have a class with instance variables & you want to expose them to the outside world.
How?
You have to define a method.
Only methods can access instance variables.
Why?
Because you’ll get an error if you don’t do this.
Here’s an example:
class Food
def initialize(protein)
@protein = protein
end
end
bacon = Food.new(21)
bacon.protein
# NoMethodError: undefined method `protein'
NoMethodError is the error you get when you ask for the value of protein without the proper setup.
What’s the solution?
You can define your own method like this:
class Food
def protein
@protein
end
end
bacon.protein
# 21
In other OOP languages this is known as a “getter” method. You define a method that gets you the value of the instance variable.
You may also want to change the value.
For that, you’ll need another method, like this one:
class Food
def protein=(value)
@protein = value
end
end
bacon.protein = 25
Imagine you’re opening a portal into the object so that you can change the value.
That’s what this is doing.
Now:
Is there a better way to define this kind of method?
Like some kind of shortcut?
Yes!
There is 🙂
That’s where attr_accessor comes in.
Ruby attr_accessor Examples
You can tell Ruby to create these methods for you with attr_accessor.
Here’s how:
class Food attr_accessor :protein def initialize(protein) @protein = protein end end
Look at this line:
attr_accessor :protein
This is a Ruby method that creates other methods for you.
What methods?
For this example, it creates:
proteinprotein=
These are the same methods we created before…
But now you don’t have to type them out.
It’s a shortcut!
attr_accessor vs attr_reader
Besides attr_accessor, you also have other kinds of accessors.
Three of them to be exact:
attr_accessorattr_readerattr_writer
What are the differences between them?
Well, attr_accessor creates both the READER & WRITER methods.
attr_readercreates only the reader.-
attr_writercreates only the writer.
In other words:
With attr_reader you can only read the value, but not change it. With attr_writer you can only change a value but not read it.
Multiple Instance Variables
Want to define multiple attribute methods?
You can do it.
But you have to use the right syntax.
Like this:
attr_reader :name, :value, :ready?
You can create as many as you want.
Watch Video Tutorial
Summary
You have learned about attribute accessors in Ruby! A set of 3 methods (attr_accessor, attr_writer & attr_reader) to access & set instance variables from outside the class.
Now it’s time to practice.