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.

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…