Skip to content

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:

puts AwesomeObject.new
#<AwesomeObject:0x00007fd9a142a748>

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:

puts 7
7
=> nil

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:

class AwesomeObject
def to_s
"This is some awesome output"
end
end

Then, once you run puts on it, the output from the to_s method will be used:

puts AwesomeObject.new
This is some awesome output

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:

class AwesomeObject
def initialize(name, age)
@name = name
@age = age
end
attr_reader :name, :age
def to_s
"This is some awesome output: #{name}, #{age}"
end
end

To go back over the puts which uses to_s and is customized in the class above:

puts AwesomeObject.new("Rob", 42)
This is some awesome output: Rob, 42

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:

AwesomeObject.new("Rob", 42).inspect
#<AwesomeObject:0x00007fd9a15720b0 @name="Rob", @age=42>

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:

class AwesomeObject
def initialize(name, age)
@name = name
@age = age
end
attr_reader :name, :age
def inspect
"This is some awesome output: #{name}, #{age}"
end
end

Then, in your IRB or console, you can run .inspect on the instance:

AwesomeObject.new("Rob", 42).inspect
=> "This is some awesome output: Rob, 42"

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.