Reflection usage in Ruby
Ruby allows you to query each object for class and superclass they are derived from as well as see modules included. Ruby reflection mechanism plays an important role in allowing you to accomplish this with relative ease.
“my string”.class //returns String
“my string”.class.superclass //returns Object
String.class //returns Class
String.class.superclass //returns Module
Moreover, you can always get a list of modules included into Class by calling on ancestors method.
String.ancestors //returns String, Enumerable, Comparable, Object, Kernel, BasicObject
The most basic class you define as in fact several modules included by default.
class MyClass
end
MyClass.ancestors //returns MyClass, Object, Kernel, BasicObject
In addition to classes, superclasses and modules, we can extract methods of objects in Ruby via its reflection properties.
Object.methods //returns name, private_class_method, object_id, new, singleton_method, method_defined?”…..
We can elso get a list of instance methods by calling instance_methods method on the instantiated class.
Often times you may need to perform a check for the existence of a particular method existence for the class of instance of a class. In this case, Ruby provides us with the following methods.
MyClass.method_defined?
MyClass.new.respond_to?
MyClass.respond_to?
If you need autocomplete feature enabled in your programming environment, you can always include irb library in your code by adding (require ‘irb/completion’) line of code into your .irbrc file. This way you can simply type a string with a dot right after it and pressing a Tab key to reveal of the string methods available to you.
Please note, you are able to see private methods when you use reflection but it does not make them available for use by you.
You can also extract instance variables in Ruby by calling instance_variables method on the instance.