为什么数组中的对象没有对象方法?

时间:2016-11-22 13:29:19

标签: arrays ruby class object

我正在尝试使用paket_obj数组创建一个模型。我的问题是为什么有2个而不是1个“paket_obj”类的对象,为什么他们没有这个类的方法呢?

我想这样做是因为我想在这个类中存储,创建,删除和操作paket_obj类的对象.paket_modul类也用于测试目的。

这是paket_modul类。没有任何事情发生

class Paket_Modul
 #Import von Klassen
 require_relative 'paket_obj'

 attr_reader :arrayofpackages

 def initialize
 @arrayofpackages = []
 @arrayofpackages << addnew_Paket
end


def addnew_Paket
   #Paket wird mit einer ID initalisiert
   newpaket = Paket_Obj.new(@arrayofpackages.last == nil ? 0 : @arrayofpackages.last.id_paket+1)
   #Objekt von Typ Paket_Obj dem Array hinzufügen
   @arrayofpackages << newpaket
end

def defineinformation_Paket(param,constantoption)
   @arrayofpackages[param].AddConstant(constantoption)
end

#Why does object in array does not have the object methods?
a = Paket_Modul.new
for param in a.arrayofpackages
  puts param
end

end

paket_obj类

class Paket_Obj
attr_accessor :mobilnumber, :emailadresse, :name_ofcertPerson, :id_paket, :id_vorgang, :firma


def initialize(id_paket, attributes = {})
@mobilnumber = attributes[:mobilnumber]
@name_ofcertPerson = attributes[:name_ofcertPerson]
@emailadresse = attributes[:emailadresse]
@firma = attributes[:firmav]
@id_paket = id_paket
@id_vorgang = attributes[:id_vorgang]
end

def AddConstant(param)
puts case param
       when 0
         @mobilnumber = '015224028625'
         @name_ofcertPerson = 'Emil Klaus'
         @emailadresse= 'email@info.de'
         @firma = 'ERTZ'
         @id_vorgang = 0
       when 1
         @mobilnumber = '015758625623'
         @name_ofcertPerson = 'Dirk Heisenberg'
         @emailadresse= 'MAIL@info.de'
         @firma = 'DFGHD'
         @id_vorgang = 1
     end
end
end

1 个答案:

答案 0 :(得分:0)

问题解决了。这只是代码中的一个错误。

首先:

 def initialize
  @arrayofpackages = []
  #This here is wrong. I wanted to initialize the array with an object but forgot to return an object in the method addnew_Paket
  #What i did was adding the reference of the method into the array
  @arrayofpackages << addnew_Paket
 end

要做到这一点,我们必须这样做:

  def initialize
   @array_of_packages = Array.new
  end

  def add_new_paket
   newpaket = PaketObj.new(@array_of_packages.last == nil ? 0 : (@array_of_packages.last.id_paket) + 1)
   @array_of_packages << newpaket
  end