What is attr_accessor?

Prateek vyas
2 min readJul 11, 2021

--

In this blog we are going to understand what is attr_accessor?

why do we need to use it?

attr_accessor acts as a attribute to the object!

I know you didn’t get my point, let’s use the words you must’ve heard before right? So the words are getter and setter!
so what if i use different words again?

Let’s be clear this time….

attr_accessor gives two different methods to the class one method is called getter and another is setter

you just read that right!

yes i said it gives two different methods.

Let’s say you have a class named King

you must’ve heard that in ancient time kings used to have multiple wifes right?

Oh i mean wives LoL!

well let’s see how that looks like in the ruby code

Setter method

In the above image i created one setter method (wife1=(wife1)) which sets the instance variable (wife1) and then i tried to call the wife1 method on king’s object which will obviously be giving me undefined method wife.

Because we have not defined it.

Let’s define it NOW!!!

getter method

Now you won’t get that undefined method errror because you’ve created one getter method who’s giving/returning us the wife’s name right?

What if i say you can do this in a single line?
YES YOU READ THAT RIGHT

YOU CAN REDUCE THE ABOVE TO METHODS TO A SINGLE LINE!

wanna know how?

Let’s do it…NOW!

attr_accessor

we’ve done that!

now what i mean is attr_accessor gives us two instance methods getter and setter

now as i said King can have 2 wives right?

let’s name them

two wives of a king

YAY! you just learnt the amazing concept! (Pardon me if i bored you LoL!)

I would like to know how the above would look like if i didn’t had attr_accessor?

--

--