AnyCompiler

attr_accessor and Encapsulation

Writing a getter and setter by hand for every instance variable is mechanical and repetitive: def x; @x; end and def x=(value); @x = value; end, over and over. attr_accessor :x generates both of those methods for you in one line. attr_reader generates only the getter (read-only from outside); attr_writer generates only the setter.

class Point
  attr_accessor :x, :y

  def initialize(x, y)
    @x = x
    @y = y
  end

  def to_s
    "(#{@x}, #{@y})"
  end
end

p = Point.new(1, 2)
puts p
p.x = 10
puts p.x
puts p
Output
(1, 2)
10
(10, 2)

p.x = 10 looks exactly like assigning a public field, but it's actually a method call (x=) that attr_accessor generated — Ruby's syntax makes a generated setter method indistinguishable at the call site from direct field access. to_s is the method puts calls automatically when asked to print an object directly, which is why puts p rendered as (1, 2) rather than some default object description. Next: inheritance and modules — class inheritance plus Ruby's mixin mechanism.

Practice exercise

Define class Point with attr_accessor :x, :y and initialize(x, y). Create Point.new(1, 2), set p.x = 10, then print p.x and p.y.