The question of ruby ​​reflection

I'm new to Ruby, so forgive me if the question is inconsistent. Can I iterate over class members, for example, through an array in Ruby? How to achieve this?

+4
source share
4 answers

You can create a class variable (array) and in the constructor ( initialize ) insert a 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 
+7
source

I think the OP may have asked if you can access the private, class, and instance variables.

Try this in irb or some program:

p YourClass.methods.sort

There you will see a bunch of methods that end with _methods or _variables. Each of them has each method, so you can easily do something like this:

 YourClass.instance_variables.each do |x| px end 
+6
source

What exactly do you mean with class members?

If you mean instance variables, you can get through instance.instance_variables . If class variables, similar to klass.class_variables .

If you want to get all the variables and methods, you additionally call instance.methods (which actually return strings and become more complex due to smoothed methods, etc.)

+6
source

You can get a list of all the constants defined in the 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 :

 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 not possible to get a list of instance variables from a module for the simple reason that the modules are not aware of instance variables, because unlike Smalltalk or Java, instance variables are not fixed by the class, they are simply dynamically added to the object as needed.

+4
source

All Articles