RubyGuides
Share this post!

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.

Example:

puts [1,2,3]

1
2
3

But when you print your own objects…

You see this:

#<Cat:0x29458e0>

Why?

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"
  end
end

puts Cat.new
# "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
  end

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

puts Cat.new("blue")
# "I'm a blue cat"

puts Cat.new("white")
# "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.

First:

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).

Then:

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:

"abc".inspect

Shows as:

"abc"

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}"
  end
end

Cat.new("white").inspect
# "Cat - id: 23316588 - color: white"

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

Video Tutorial

Summary

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.

Leave a Comment: