Reason #169 •
June 18th, 2026
Observing objects via Object#inspect
When using IRB, you have surely noticed that after each expression, Ruby prints the result of that expression:
IRB
2 + 2
# => 4
"Hello, world!"
# => "Hello, world!"
[1, 2, 3].map { |x| x * 2 }
# => [2, 4, 6]
{ a: 1, "b" => 2 }
# => {a: 1, "b" => 2}
class User
attr_reader :name
def initialize(name)
@name = name
end
end
User.new("Sam")
# => #<User:0x00007f9c8b0c8d8 @name="Sam">
But have you ever wondered how Ruby decides what to print? The answer is that Ruby calls the #inspect method on the resulting object to get a string representation of it.
By overriding #inspect in our classes, we can customize how instances of those classes are displayed:
Ruby
class User
attr_reader :name
def initialize(name)
@name = name
end
def inspect
"👤 #{@name}"
end
end
User.new("Sam")
# => 👤 Sam
This is especially useful for big objects where the default #inspect output can be overwhelming.
Other situations where #inspect is invoked include passing objects into the p and pp methods, which are intended for debugging output.
History
Object#inspect has been part of Ruby since its inception.