RubyGuides
Share this post!

How to Use attr_accessor, attr_writer & attr_reader

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.

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:

  • protein
  • protein=

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_accessor
  • attr_reader
  • attr_writer

What are the differences between them?

Well, attr_accessor creates both the READER & WRITER methods.

attr_reader creates only the reader.

attr_writer creates only the writer.

This means that with attr_reader you can only read the value, but not change it. And with attr_writer you can only change it but not read it.

Multiple Instance Variables

If you want to define attribute methods for multiple variables you can do that.

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!

Now it’s time to practice.

Leave a Comment:

2 comments
Daniel says last month

Good job, bro! you continue to this way… Easy, basic and simple teaching of “Atrribute accessor”

Reply
    Jesus Castello says last month

    Thank you 🙂

    Reply
Add Your Reply