RFS: Attr Reader, Writer, Accessor - 011

In ruby a lot can be achieved in a single line of code. Defining our own getters and setters is usually done when we need custom behavior for all other cases there is already something built in ruby. We'll cover attr_reader, attr_writer and attr_accessor in this post.

Let's take a look at how we can clean up our code.

class Product  TYPES = ['game', 'food']    def name    @name  end    def name=(str)    @name = str  endend

In this case we are defining a getter and setter method for our attribute @name imagine if we had 4, 5 or even 10 attributes for our class. It would be extremely wasteful if we had to define setters and getters for all of them.


Sometimes you want to define an attribute that is read-only in a class in this case we can use attr_reader.

class Product  TYPES = ['game', 'food']    attr_reader :name    def name=(str)    @name = str  endend

attr_reader replaces our getter.


If we need our attribute to be writable we can use attr_writer

class Product  TYPES = ['game', 'food']    attr_reader :name  attr_writer :nameend

attr_writer replaces our setter.


If we want our attribute to be both readable / writable we can use attr_accessor like so.

class Product  TYPES = ['game', 'food']    attr_accessor :nameend

That's it for this post! Hope that clears up how to define attributes in your ruby class.