Intermingling attr_accessor and an initialize method in one class

后端 未结 4 1499
梦毁少年i
梦毁少年i 2021-01-30 02:59

I see code like:

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

I understand this allows me to do things like person = Pe

4条回答
  •  旧时难觅i
    2021-01-30 03:23

    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.

提交回复
热议问题