Bird
Raised Fist0
RubyHow-ToBeginner · 3 min read

How to Override to_s in Ruby: Simple Guide with Examples

In Ruby, you override to_s by defining a new to_s method inside your class. This method should return a string that represents the object in the way you want it to appear when converted to a string.
📐

Syntax

To override to_s, define a method named to_s inside your class. This method must return a string that describes the object.

Parts:

  • def to_s: starts the method definition
  • return a string: the string representation of the object
  • end: ends the method definition
ruby
class MyClass
  def to_s
    "custom string representation"
  end
end
💻

Example

This example shows a Person class overriding to_s to return the person's name and age as a string.

ruby
class Person
  attr_accessor :name, :age

  def initialize(name, age)
    @name = name
    @age = age
  end

  def to_s
    "Name: #{@name}, Age: #{@age}"
  end
end

person = Person.new("Alice", 30)
puts person.to_s
Output
Name: Alice, Age: 30
⚠️

Common Pitfalls

Common mistakes when overriding to_s include:

  • Not returning a string (e.g., returning a number or nil)
  • Forgetting to define to_s inside the class
  • Using puts inside to_s instead of returning a string

Always ensure to_s returns a string value.

ruby
class WrongExample
  def to_s
    puts "This prints but returns nil"
  end
end

obj = WrongExample.new
puts obj.to_s # prints nothing useful

class RightExample
  def to_s
    "This is the correct string"
  end
end

obj2 = RightExample.new
puts obj2.to_s # prints the string
Output
This prints but returns nil This is the correct string
📊

Quick Reference

Remember these tips when overriding to_s:

  • Always return a string, not print it.
  • Use instance variables to build meaningful output.
  • Keep the string simple and clear for easy reading.
✅

Key Takeaways

Override to_s by defining it inside your class to customize string output.
to_s must return a string, never print or return nil.
Use instance variables inside to_s to show useful object details.
Test your to_s method by calling it or using puts on the object.
Avoid side effects like printing inside to_s; keep it pure.