什么已经有效
我可能误解了你的问题,但看起来你的代码大部分按原样工作。我对它进行了一些重构,以便更容易地了解发生了什么,但是在对象初始化期间使用类变量进行自注册的基本方法似乎是合理的。考虑:
class Suggestion
@@all = []
def initialize(type, participants)
@type = type
@participants = participants
@@all << self
end
def self.all
@@all
end
end
s1 = Suggestion.new :foo, %w[Alice Bob]
#=> #<Suggestion:0x00007f9671154578 @participants=["Alice", "Bob"], @type=:foo>
s2 = Suggestion.new :bar, %w[Charlie Dana]
#=> #<Suggestion:0x00007faed7113900 @participants=:bar, @type=:foo>
Suggestion.all
#=>
[#<Suggestion:0x00007f9671154578 @participants=["Alice", "Bob"], @type=:foo>,
#<Suggestion:0x00007f9671089058
@participants=["Charlie", "Dana"],
@type=:bar>]
哪些方面可能需要改进
您可能只需要类或实例方法,对存储在中的每个实例(或从特定实例中选择的元素)“做某事”@@all。例如:
# print the object ID of each instance of Suggestion
Suggestion.all.map { |suggestion| suggestion.object_id }
#=> [240, 260]
您可能还想使用数组#select https://ruby-doc.org/core-3.0.0/Array.html#method-i-select提取满足定义条件的特定实例,或者数组#map https://ruby-doc.org/core-3.0.0/Array.html#method-i-map对您的匹配实例执行某些操作。例如:
# re-open the class to add some getter methods
class Suggestion
attr_reader :type, :participants
end
# only operate on instances of a given type
Suggestion.all.select { |s| s.type == :foo }
#=> [#<Suggestion:0x00007f9671154578 @participants=["Alice", "Bob"], @type=:foo>]
# invoke Suggestion#participants on matching instances
Suggestion.all.map { |s| s.participants if s.type == :bar }.compact
#=> [["Charlie", "Dana"]]
只要你有一个可以迭代的集合(例如你的类'@@all数组),您可以根据需要对部分或全部实例进行过滤、映射或以其他方式进行操作。当然还有更复杂的方法,但我会努力使其尽可能简单。