Intermingling attr_accessor and an initialize method in one class

David picture David · May 20, 2013 · Viewed 27.3k times · Source

I see code like:

class Person
  def initialize(name)
    @name = name
  end
end

I understand this allows me to do things like person = Person.new and to use @name elsewhere in my class like other methods. Then, I saw code like:

class Person
  attr_accessor :name
end

...

person = Person.new
person.name = "David"

I'm just at a loss with these two methods mesh. What are the particular uses of def initialize(name)? I suppose attr_accessor allows me to read and write. That implies they are two separate methods. Yes? Want clarifications on def initialize and attr_accessor and how they mesh.

Answer

Sergio Tulentsev picture Sergio Tulentsev · May 20, 2013

initialize and attr_accessor have nothing to do with each other. attr_accessor :name creates a couple of methods:

def name
  @name
end

def name=(val)
  @name = val
end

If you want to set name upon object creation, you can do it in the initializer:

def initialize(name)
  @name = name
  # or
  # self.name = name
end

But you don't have to do that. You can set name later, after creation.

p = Person.new
p.name = "David"
puts p.name # >> "David"