Read more

How to examine an unknown Ruby object

Dominik Schöler
September 26, 2018Software engineer at makandra GmbH

When debugging your application, you will come across objects created by some gem or framework. You don't have the source code at hand, still need to inspect this object. Here are some tools to do so:

Relevant methods

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

@object.methods - Object.instance_methods returns a list of methods excluding methods inherited from Object. This makes the methods list drastically more relevant. You can also try subtracting other base classes like ActiveRecord::Base.methods etc.
To further narrow it down you can also just look at public methods via @object.public_methods - Object.public_instance_methods.

Filtering method list

@object.methods.grep /keyword/ comes handy when you have an idea on how a method is called. It filters the list of method names with a regular expression.

Instance variables

@object.instance_variables returns all instance variables defined on the object. Access them with @object.instance_variable_get :@varname, modify with @object.instance_variable_set :@varname, value.

Using a debugger

A debugger can also be useful to learn more about an object.
For example ruby-debug has a command outline @object will show all available methods and variables in a well arranged format.
Pry has a similar command named ls.


Also see

Posted by Dominik Schöler to makandra dev (2018-09-26 08:59)