How to Create Ruby Objects That Describe Themselves

In this article you’ll learn how the Ruby inspect method works & why do we use it.

When you print a string or array you see its contents.


puts [1,2,3]


But when you print your own objects…

You see this:



Because you haven’t told Ruby how to display this class in a way that makes sense.

You can change this if you define a method like to_s.

Let’s see how that works!

Implementing to_s

When you use puts with an object, Ruby calls the to_s method to get a string representation of the object.

By default you get the class name (Cat)…

Plus some number that represents the object_id in hexadecimal format (0x29458e0).

Here’s how to change that:

class Cat
  def to_s
    "I'm a cat"

# "I'm a cat"

If your class has instance variables, you can make them part of your object description.

Like this:

class Cat
  attr_reader :color

  def initialize(color)
    @color = color

  def to_s
    "I'm a #{color} cat"

# "I'm a blue cat"

# "I'm a white cat"

Now when you print this object you’ll see more useful information.

Isn’t that cool?

Ruby Inspect Method

You can represent an object in two possible ways.


Using to_s.

This is what you want your users to see when you display the object.

For example, with a time object, you would display the time in a way that makes sense (2018-12-28 19:17:28), instead of showing how the time is actually stored (1546021067).


You can inspect objects, this gives you a more raw version of the object.

What’s the difference?

  • Define to_s so that when you use puts, it will show this particular view of the object.
  • Define inspect to help yourself & other developers with debugging.

Here’s an example:


Shows as:


Inspect keeps the quotation marks, and special characters (like \n for newlines) become visible.

The best part?

You can implement the inspect method in your own classes 🙂

Here’s how:

class Cat
  attr_reader :color

  def inspect
    "Cat - id: #{object_id} - color: #{color}"
# "Cat - id: 23316588 - color: white"

That’s how you can create objects that describe themselves!

Video Tutorial

[responsive_video type=’youtube’ hide_related=’0′ hide_logo=’0′ hide_controls=’0′ hide_title=’0′ hide_fullscreen=’0′ autoplay=’0′][/responsive_video]


You have learned how to use the Ruby inspect & to_s methods to build better classes!

If you liked this article please share it so more people can find it.

Thanks for reading.