How to Use attr_accessor When Building a New Class

Ruby allows you to build classes to represent a group of items that all have the same characteristics. Then, you can build relationships between classes in order to represent more complex behaviors. The great news is that Ruby has accessors that perform the get/set methods necessary for all connected classes to talk to each other.

For example, let’s say you are a whiskey aficionado and wish to build a program that allows people to submit reviews on different types of whiskey they have tried. You want to create whiskey Release, Review, and User classes with the Review as a join table.

With this knowledge, you can start sketching out the attributes you want new objects within that class to have. We’ll start our whiskey release class with a name attribute and write some methods to make it easier to access through our other classes.

class Release
  def initialize(name)  {{This sets our name}}
    @name = name
  end

  def name=(name)  {{This allows us to 'get' the name}}
  end
end

Now that we have the name attribute taken care of, we decide that it’d also be good for our Release class to be initialized with score and price. In order to set those up, we will need to do a get and a set for each of those two items.

All of that typing is kind of a bummer though, right? In addition to taking longer to set up each class, there’s a greater chance of human error because we have to type a lot of repetitive methods.

class Release
  attr_accessor :name     {{This is our get method now}}

  def initialize(name)  
    @name = name
  end
end

That’s definitely better! Now we can really breeze through our initialization process with our additional attributes…

Hopefully, it helps to see what the attr_accessor is actually doing and the method that it replaces.

class Release
  attr_accessor :name, :score, :price

  def initialize(name, score, price)  
    @name, @score, @price = name, score, price
  end
end