我正在尝试从循环内初始化一个类的实例,并且我不确定如何命名该对象,以便每次迭代都有一个新名称,因此我没有调用五个对象/实例'my_animal'?
my_array = ["Fluffy", "Lala", "Jo", "Cersei", "Berlin"]
my_array.each do |e|
my_animal = Animal.new(e)
end
class Animal
attr_accessor :name
def initialize (name)
@name = name
end
end
答案 0 :(得分:2)
你可以这样做:
my_array = ["Fluffy", "Lala", "Jo", "Cersei", "Berlin", "Jo"]
arr = my_array.each_with_index.with_object([]) do |(e,i),a|
a << Animal.send(:new, "#{e}#{i}")
end
#=> [#<Animal:0x007fe3e4087b20 @name="Fluffy0">,
# #<Animal:0x007fe3e4087a80 @name="Lala1">,
# #<Animal:0x007fe3e40879e0 @name="Jo2">,
# #<Animal:0x007fe3e4087940 @name="Cersei3">,
# #<Animal:0x007fe3e4087878 @name="Berlin4">,
# #<Animal:0x007fe3e31d5618 @name="Jo5">]
arr.map(&:name)
#=> ["Fluffy0", "Lala1", "Jo2", "Cersei3", "Berlin4", "Jo5"]
或者,以下方式传达了其他信息:
my_array = ["Fluffy", "Lala", "Jo", "Cersei", "Lala", "Jo", "Berlin", "Jo"]
arr = my_array.each_with_object([]) do |s,a|
instance = a.reverse.find { |i| i.name =~ /^#{s}/ }
if instance
old_name = instance.name
prefix, nbr = old_name.split(/(\d+)/)
new_name = "#{prefix}#{((nbr.to_i)+1).to_s}"
else
new_name = "#{s}0"
end
a << Animal.send(:new, new_name)
end
#=> [#<Animal:0x007fe3e402e458 @name="Fluffy0">,
# #<Animal:0x007fe3e402e1b0 @name="Lala0">,
# #<Animal:0x007fe3e402dc38 @name="Jo0">,
# #<Animal:0x007fe3e402d120 @name="Cersei0">,
# #<Animal:0x007fe3e402c540 @name="Lala1">,
# #<Animal:0x007fe3e4097d68 @name="Jo1">,
# #<Animal:0x007fe3e4096d00 @name="Berlin0">,
# #<Animal:0x007fe3e4096698 @name="Jo2">]
arr.map(&:name)
#=> ["Fluffy0", "Lala0", "Jo0", "Cersei0", "Lala1", "Jo1", "Berlin0", "Jo2"]
答案 1 :(得分:1)
将所有新对象推送到数组而不是静态变量,然后您可以用数字方式访问它们。
答案 2 :(得分:1)
您可以尝试将它们放入哈希,然后您可以像my_animals["Lala"]
一样访问它们。
class Animal
attr_accessor :name
def initialize (name)
@name = name
end
end
my_array = ["Fluffy", "Lala", "Jo", "Cersei", "Berlin"]
my_animals = Hash.new
my_array.each do |e|
my_animals[e] = Animal.new(e)
end
答案 3 :(得分:1)
您的代码发生了什么,以及您在my_animal = Animal.new(e)
上创建的每个实例都丢失了。你必须在某些结构上跟踪所有这些。像字典(哈希)或数组。
这可能会有所帮助:
class Animal
attr_accessor :name
def initialize (name)
@name = name
end
end
my_array = ["Fluffy", "Lala", "Jo", "Cersei", "Berlin"]
my_instances = {}
my_array.each do |e|
my_animal = Animal.new(e)
my_instances[e] = my_animal
end
现在您有一个带有对象的数组的名称(字符串)。它将类似于:
my_instance = { "Fluffy" => #<Animal:0x0000000280d638 @name="Fluffy">,
"Lala" => #<Animal:0x0000000280d5e8 @name="Lala">,
"Jo" => #<Animal:0x0000000280d598 @name="Jo">,
"Cersei" => #<Animal:0x0000000280d548 @name="Cersei">,
"Berlin" => #<Animal:0x0000000280d4f8 @name="Berlin">
}