← Back to Ruby Course | Chapter 9: OOP | Lesson 4 of 7

attr_accessor

In this page:

  1. attr_accessor

attr_accessor

attr_accessor :name automatically generates both a getter (name) and setter (name=) method for an instance variable, saving you from writing them manually. attr_reader generates only a getter, and attr_writer generates only a setter, for when you want to restrict read or write access. This is one of Ruby's most commonly used metaprogramming conveniences.

Note: Use attr_reader for read-only properties you don't want external code to modify directly.

Example: attr_accessor

markup
class Product
  attr_accessor :name, :price

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

p = Product.new("Pen", 2.5)
puts p.name
p.price = 3.0
puts p.price
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.