Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby reflection question

Tags:

class

ruby

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?

like image 401
Grant Smith Avatar asked Nov 28 '22 19:11

Grant Smith


1 Answers

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
like image 197
fantactuka Avatar answered Jan 27 '23 20:01

fantactuka