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.
You have to define a method.
Only methods can access instance variables.
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.
Is there a better way to define this kind of method?
Like some kind of shortcut?
There is 🙂
attr_accessor comes in.
Ruby attr_accessor Examples
You can tell Ruby to create these methods for you with
class Food attr_accessor :protein def initialize(protein) @protein = protein end end
Look at this line:
This is a Ruby method that creates other methods for you.
For this example, it creates:
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
attr_accessor, you also have other kinds of accessors.
Three of them to be exact:
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:
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.
attr_reader :name, :value, :ready?
You can create as many as you want.
Watch Video Tutorial
You have learned about attribute accessors in Ruby. A set of 3 methods (
attr_reader) to access & set instance variables from outside the class.
Now it’s time to practice!