I am new to Ruby so forgive me if the question is inconsistent. Can I iterate over class members like through array in Ruby? How do I achieve this?
You can create a class variable (array) and in constructor (initialize
) push new instance into it.
class Foo
@@instances = []
attr_accessor :name
def initialize name
@name = name
@@instances << self
end
def self.instances
@@instances
end
end
Foo.new("test")
Foo.new("test2")
Foo.instances.each do |i|
puts i.name
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With