OOP: Attributes (attr_accessor)

💎 Ruby Lesson 11 Intermediate

Instance variables inside Ruby objects are strictly private by default. In this lesson, we will look at how to expose properties using getters, setters, and attr_accessor shorthand.

1 Getter/Setter shorthands: attr_reader, attr_writer, attr_accessor

Rather than writing verbose getter and setter methods manually, Ruby provides three clean attribute helper methods:

  • attr_reader: Automatically generates read-only getter methods.
  • attr_writer: Automatically generates write-only setter methods.
  • attr_accessor: Automatically generates both getter and setter methods.
2 Attribute Accessors Code

Let's run a program declaring classes and instantiating objects using attr_accessor properties:

Ruby — Attributes ▶ Run Code
class Account
  # Generates getter and setter for owner and balance
  attr_accessor :owner, :balance

  def initialize(owner, balance)
    @owner = owner
    @balance = balance
  end
end

acc = Account.new("Bob", 500.0)
acc.balance = 700.0 # Invokes automatic setter

puts "Owner: #{acc.owner}"
puts "Balance: $#{acc.balance}"
3 Code Challenge
Challenge: Create an `Employee` class. Make `name` read-only (using `attr_reader`) and `salary` readable and writable (using `attr_accessor`). Test your design by instantiating it and trying to edit both properties.