Skip to content

Instantly share code, notes, and snippets.

@alexaltair
Last active December 18, 2015 21:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexaltair/5851473 to your computer and use it in GitHub Desktop.
Save alexaltair/5851473 to your computer and use it in GitHub Desktop.
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