attr_accessor (Ruby)

attr_accessor is a Ruby shortcut that auto-generates getter and setter methods for instance variables. attr_reader makes read-only accessors and attr_writer makes write-only ones.

Ruby

Instance variables (@name) are private to an object — outside code can't read or set them directly. Rather than writing boilerplate def name; @name; end and def name=(v); @name = v; end, you call attr_accessor :name once and Ruby generates both methods for you.

The three variants give you control: attr_reader :x generates only the getter, attr_writer :x only the setter, and attr_accessor :x both. They accept multiple symbols at once: attr_accessor :name, :age. Each is actually a class method (from Module) that defines methods via metaprogramming.

Because attribute access goes through methods, you can later replace a generated accessor with a custom one (e.g. to validate or compute) without changing how callers use it — preserving Ruby's uniform access principle.

Syntax

class User
  attr_accessor :name
  attr_reader :id
end

Examples

Ruby

class Dog
  attr_accessor :name
  def initialize(name); @name = name; end
end

d = Dog.new("Rex")
puts d.name
d.name = "Max"
puts d.name

Output:

Rex
Max

Learn it in a lesson

See also

Back to the Dictionary