Intermingling attr_accessor and an initialize method in one class

后端 未结 4 1451
梦毁少年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条回答
  •  日久生厌
    2021-01-30 03:24

    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"
    

提交回复
热议问题