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

attr_accessor

attr_accessor creates the ways to read and change a value on an object in a single line, like putting a window and a door on a box. Without it you would write each one by hand.

In this page:

  1. attr_accessor
Syntax
ruby
class ClassName
  attr_accessor :attribute
  attr_reader :read_only
  attr_writer :write_only
end

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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Assigning inside a method with name = "x" and expecting the attribute to change, when it creates a local variable; use self.name = "x".
  2. Using attr_accessor when only reading is needed, when attr_reader is safer.
  3. Writing attr_accessor name without the colon, which looks for a variable name.
🔒

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.