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
self.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
I think the OP might have been asking about whether you can get access to private, class, and instance variables.
Try this out in irb or some program:
p YourClass.methods.sort
In there you should see a bunch of methods that end in _methods or _variables. Each of these has the each method so you can easily do something like this:
YourClass.instance_variables.each do |x|
p x
end
What exactly do you mean with class members?
If you mean instance variables, you can get the via instance.instance_variables
. If class variables, similarly with klass.class_variables
.
If you want to get all variables and methods, you call additionally instance.methods
(which actually return strings, and gets trickier because of the aliased methods, etc.)
You can get a list of all constants defined in a module using Module#constants
. Example:
Object.constants.sort
# => [:ARGF, :ARGV, :ArgumentError, :Array, :BasicObject, :Bignum, ... ]
For methods, you can call one of the various Module#methods
methods:
Object.methods.sort
# => [:!, :!=, :!~, :<, :<=, :<=>, :==, :===, :=~, :>, :>=, :__id__, ... ]
You can get a list of all the various methods
methods using reflection itself (yay meta):
Module.methods.sort.grep /methods/
# => [:instance_methods, :methods, :private_instance_methods, :private_methods,
# => :protected_instance_methods, :protected_methods, :public_instance_methods,
# => :public_methods, :singleton_methods]
It is impossible to get a list of the instance variables from a module for the simple reason that modules don't know about the instance variables, since unlike Smalltalk or Java, the instance variables aren't fixed by the class, they are simply dynamically added to the object as needed.