Table of contents
1.
Introduction
2.
Reflection and Metaprogramming
3.
What are Method objects?
4.
Problem 
5.
Solution
6.
Discussion
7.
Frequently Asked Questions
7.1.
What are Methods in Ruby?
7.2.
What is Metaprogramming in ruby?
7.3.
What is Ruby Method?
7.4.
What is the main object in Ruby?
7.5.
Are variables objects in Ruby?
8.
Conclusion
Last Updated: Mar 27, 2024
Medium

Listing an Object’s Methods in Ruby

Author yuvatimankar
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Ruby is a dynamic, open-source programming language focusing on productivity and simplicity. The syntax of Ruby is natural and easy to understand for the users. Ruby is a popular language for many things, from web development to data analysis. Ruby programming language is highly flexible, and developers can change how the language works due to its flexibility. Ruby is an interpreted language. 

In this blog, we will discuss the Listing of an object's Method in Ruby with the help of some examples. So stay till the end!

Reflection and Metaprogramming

Reflection simply means that a program can evaluate its state and its structure. The reflection API allows a program to change its state and structure. The ruby's reflection API, dynamic nature, and control structures make it a perfect language for Metaprogramming. Metaprogramming is defined as writing programs or frameworks that help us to write programs. Metaprogramming connects closely to the idea of writing domain-specific languages(DSLs). The domain-specific language uses method invocations and blocks like they were keywords in a task-specific extension to the language.

What are Method objects?

method in ruby is a named block of parameterized code connected with multiple objects. Many Languages compare functions and methods, but because ruby is a purely object-oriented language, all methods are true methods associated with at least one object. Methods are an important part of syntax in ruby, but they are not values that Ruby programs can operate on. 

Ruby has strong metaprogramming capabilities, and methods can be represented as instances of the Method class. Invoking a method through a Method Object is less efficient than invoking it directly. Method objects are not generally used as frequently as procs and lambdas. The Object class defines a method named "method." When we Pass it a method name as a string or a symbol, it returns a Method object representing the designated Method of the receiver. 

For example:

m = 0.method(:succ)  # A Method representing the succ method of Fixnum 0
You can also try this code with Online Ruby Compiler
Run Code

Problem 

Let's say we have given an unfamiliar object, and we want to see what methods are available to call.

Solution

All Ruby objects execute the object#methods method. It will return an array that contains the names of the object's public instance methods:

Object.methods 
# => ["name", "private_class_method", "object_id", "new", 
# "singleton_methods", "method_defined?", "equal?", … ]
You can also try this code with Online Ruby Compiler
Run Code


For getting a list of the singleton methods of some objects, we have to use the method known as Object1#singleton_methods:

Object1.singleton_methods    # => []
Fixnum1.singleton_methods    # => ["induced_from"] 
class NinjaClass
 def NinjaClass.my_singleton_method 
 end 
 def my_instance_method 
 end
end 
NinjaClass.singleton_methods    # => ["my_singleton_method"]
You can also try this code with Online Ruby Compiler
Run Code

Now, to list the instance methods of a class, we have to call instance_methods on the object. This allows us to list the instance methods of a class without instantiating the class:

''.methods == String.instance_methods         # => true
You can also try this code with Online Ruby Compiler
Run Code


The output of these methods can be more useful when they are sorted, therefore:

Object1.methods.sort
You can also try this code with Online Ruby Compiler
Run Code


Object1.methods.sortRuby also specifies some elementary predicates along the same lines. To look at whether a class defines a specific instance method, call method_defined? On the class or respond_to? On the instance class. And to also see call respond_to? On the instance class:

MyClass.method_defined? :my_instance_method   # => true  
MyClass.new.respond_to? :my_instance_method   # => true   
MyClass.respond_to? :my_instance_method       # => false  
MyClass.respond_to? :my_singleton_method      # => true 
You can also try this code with Online Ruby Compiler
Run Code

Discussion

When you are in an interactive session of ruby, we need to see what specific Method is called and which Method an object supports. If we are using a library like Facets and Rails or our code has been adding methods to the built-in classes, it is also considered reliable.

The below table is doing to discover protected, public, and private methods:

Just because we can see the names of protected and private methods in a table does not mean we can call the methods or respond_to? Will find them:

String.private_instance_methods.sort 
# => [:Array, :Complex, :Float, :Hash, :Integer, :Rational, :String, :__callee__, :__dir__, :__method__, :`, :abort, :at_exit, :autoload, :autoload?, :binding, :block_given?, :caller, :caller_locations, ...] 
String.new.respond_to? :autoload?               # => false 
String.new.autoload? 
# NoMethodError: private method 'autoload?' called for "":String
You can also try this code with Online Ruby Compiler
Run Code

Frequently Asked Questions

What are Methods in Ruby?

A method in ruby is a named block of parameterized code connected with multiple objects. Invoking a method through a Method Object is less efficient than invoking it directly. Method objects are not generally used as frequently as procs and lambdas.

What is Metaprogramming in ruby?

Metaprogramming in ruby is a technique by which you can write code that writes code by itself dynamically at runtime. In simple words, we can define methods and classes during runtime.

What is Ruby Method?

A method in Ruby is a set of expressions that returns a value. Within a method, you can set your code into subroutines that can be quickly initiated from other areas of their program.

What is the main object in Ruby?

In ruby, everything occurs in the context of some objects. The object at the highest level is called the "main." It is basically an instance of an object with the property that any methods defined in the main are added as the object's instance method.

Are variables objects in Ruby?

A variable in ruby is nothing but a label or tag for a container. A variable can contain almost everything like a string, an array, a hash, etc.

Conclusion

In this article, we have discussed reflection and meta-programming, and then we have seen how to list an object's Method in ruby with the help of an example. We started with the introduction of ruby, then we saw reflection and meta-programming concepts, and then the listing of an object's Method in ruby with the help of an example.

If you want to learn more about such topics, you can see  Introduction to ruby on railsDirectory Structure in RubyRuby on Railsand Ruby vs. Python. Also, refer to the Official Documentation and Ruby Koans. You can explore some more articles on For Loop in RubyOperators in Ruby, or directly access the Coding Ninjas Studio for our courses.

You can also refer to our guided path on Coding Ninjas Studio to upskill yourself in Data structure and algorithmsCompetitive Programming, Javascriptand System Design. Do upvote our blogs if you find them helpful and engaging!

Happy learning!

Live masterclass