gpt4 book ai didi

ruby - 如何从 Ruby 中的循环创建类的实例?

转载 作者:太空宇宙 更新时间:2023-11-03 17:32:51 25 4
gpt4 key购买 nike

我试图从一个循环中初始化一个类的实例,但我不确定如何命名该对象,以便它在每次迭代时都有一个新名称,所以我没有五个对象/实例都被调用“我的动物”?

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

最佳答案

你可以这样做:

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"]

关于ruby - 如何从 Ruby 中的循环创建类的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28664032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com