Initializing Instance Variable as an Array - Ruby

被刻印的时光 ゝ 提交于 2020-01-01 06:27:50

问题


I'm trying to initialize and instance variable as an array as follows:

  class Arch < ActiveRecord::Base  
  attr_accessor :name1

    def initialize
      @name1 = []
    end

    def add_name1(t)
      @name1 << t
    end

  end

When I try Arch.new in a console session I get (Object doesn't support #inspect). What's up? How do I make an instance array variable? I tried to follow this like so:

class Arch < ActiveRecord::Base
attr_accessor :name1

  def after_initialize
    @name1 = []
  end

  def add_name1(t)
    @name1 << t
  end

end

and my @name1 was still a NilClass. :/


回答1:


You are overriding ActiveRecord's initialize method. Try using super:

def initialize(*args, &block)
   super 
   @name1 = []
end



回答2:


You are overiding the initialize method of ActiveRecord::Base. When creating a new instance of your class only your initilize will be called. All the instance variables that ActiveRecord::Base would have created are uninitialized and #inspect fails. In order to fix this you need to call the constructor of your base class (using super)

class Arch < ActiveRecord::Base  

  attr_accessor :name1
  def initialize
    super
    @name1 = []
  end

  def add_name1(t)
    @name1 << t
  end
end


来源:https://stackoverflow.com/questions/8072952/initializing-instance-variable-as-an-array-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!