I see code like:
class Person
def initialize(name)
@name = name
end
end
I understand this allows me to do things like person = Pe
I think you consider initialize
as a constructor. To be precise, it is not. The default constructor is the new
method on the class, and initialize
is called by that method. If you do not define initialize
, you can still create an object with new
because initialize
is not the constructor itself. In that case, the default initialize
does nothing. If you do define initialize
, then that is called right after the object creation.
The statement @foo = ...
and attr_accessor :foo
are different. The former assigns a value to the instance variable @foo
, whereas the latter lets you access @foo
via methods foo
and foo=
. Without the latter, you can still access @foo
by directly describing so.