将实例变量初始化为数组—Ruby

时间:2021-06-25 23:34: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:

当我试着拱门。在我获得的控制台会话中是新的(对象不支持#inspect)。有什么事吗?如何创建实例数组变量?我试着这样做:

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. :/

我的@name1还是一个NilClass。:/

2 个解决方案

#1


9  

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

您正在重写ActiveRecord的initialize方法。试着用超:

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

#2


3  

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)

您正在覆盖ActiveRecord: Base的初始化方法。在创建类的新实例时,只调用初始化。ActiveRecord::Base将创建的所有实例变量都未初始化,#inspect失败。为了解决这个问题,您需要调用基类的构造函数(使用super)

class Arch < ActiveRecord::Base  

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

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

#1


9  

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

您正在重写ActiveRecord的initialize方法。试着用超:

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

#2


3  

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)

您正在覆盖ActiveRecord: Base的初始化方法。在创建类的新实例时,只调用初始化。ActiveRecord::Base将创建的所有实例变量都未初始化,#inspect失败。为了解决这个问题,您需要调用基类的构造函数(使用super)

class Arch < ActiveRecord::Base  

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

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