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.
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"