Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Quick explanation of attribute accessors.

In class definitions,

attr_accessor :name, :email, :phone_number

is the same as

attr_reader :name, :email, :phone_number
attr_writer :name, :email, :phone_number

These two expand further;

attr_reader :name, :email, :phone_number

is the same as

def name
  @name
end

def email
  @email
end

def phone_number
  @phone_number
end

Recall that Ruby returns the last line of every method, so the above things return the stored instance variable. And

attr_writer :name, :email, :phone_number

is the same as

def name=(new_value)
  @name = new_value
end

def email=(new_value)
  @email = new_value
end

def phone_number=(new_value)
  @phone_number = new_value
end

Naming a method with an equal sign at the end is a special signal to Ruby to override the = method. This allows you to write thing_instance.name = new_name.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.