How to inspect a Ruby Object
Imagine this, you adding a new object in your view, you reload the page, and you are greeted with Undefined method for nil:NilClass
. “Ok, I’ll just print the object”, you think to yourself:
Well, that didn’t help. Let’s go over the ways to print and inspect Ruby objects.
Printing an Object
First, what happens when you print an object?
When you puts
an object instance it will call .to_s
method on that object. In the cases of built-in Object types in Ruby, this is handled for you. Such as when you puts
a number:
When you do that on an object, like above, the default behavior of to_s
on an object is to print the Object’s class name (this part AwesomeObject
) and the object_id
(this part 0x00007fd9a142a748>
).
We can update the class to include a to_s
to control the output of an object’s instance in a puts
statement:
Then, once you run puts
on it, the output from the to_s
method will be used:
Inspecting an Object
Another method defined on all objects and usually overridden by the specific uses-cases of the individual classes is the inspect
method.
Let’s make out AwesomeObject
a little more complicated:
To go back over the puts
which uses to_s
and is customized in the class above:
Now, by default, the inspect method will print out the class name and object_id
, much like the build in to_s
method on the Object
class. Then it will display the attributes/instance methods on the object. This it would display the name
and age
, like so:
Just like the to_s
method used in puts
, you can also customize and override the inspect
method in your own class. Imagine we used the following inspect
method and called inspect
on the object’s instance:
Then, in your IRB or console, you can run .inspect
on the instance:
There you have it! Two ways to get the data from an object and how you can override them! I implore you to use puts
and .inspect
on the objects you may use daily, such as ActiveRecord objects, instances from gems, or clients such as HTTP clients or API clients. You will usually be able to see relevant information to debug any issue you come across.