gpt4 book ai didi

ruby - 在创建时将类实例收集到数组中

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

class Person
attr_accessor :name

def initialize(name)
@@name = name
people.push($)
end
end

它不必在初始化函数中。我只想要所有创建的人的数组。

p1 = Person.new("joe")
p2 = Person.new("rick")
people.inspect #-->would return [p1, p2]

最佳答案

如果您只需要Person 的所有实例的列表,则无需在创建时添加它们。只需通过以下方式访问它们:

ObjectSpace.each_object(Person).to_a

关于ruby - 在创建时将类实例收集到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17289068/

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