0
0
Rubyprogramming~5 mins

To_s method for string representation in Ruby

Choose your learning style9 modes available
Introduction

The to_s method changes an object into a string. This helps when you want to show or use the object as text.

When you want to print an object in a readable way.
When you need to combine an object with other text.
When saving or sending data as text.
When debugging to see what an object contains.
When converting numbers or other types to strings for display.
Syntax
Ruby
object.to_s

Every object in Ruby has a to_s method.

You can define your own to_s method inside a class to customize how objects turn into strings.

Examples
Convert a number to a string.
Ruby
123.to_s
# => "123"
Convert a boolean to a string.
Ruby
true.to_s
# => "true"
Custom to_s method in a class to show a friendly message.
Ruby
class Person
  def initialize(name)
    @name = name
  end

  def to_s
    "Person named #{@name}"
  end
end

p = Person.new("Anna")
puts p.to_s
Sample Program

This program creates a Book object and prints it as a string using the custom to_s method.

Ruby
class Book
  def initialize(title, author)
    @title = title
    @author = author
  end

  def to_s
    "\"#{@title}\" by #{@author}"
  end
end

book = Book.new("Ruby Basics", "Sam")
puts "Book info: " + book.to_s
OutputSuccess
Important Notes

If you don't define to_s in your class, Ruby shows a default string like #<ClassName:object_id>.

Use to_s to make your objects easier to understand when printed or logged.

Summary

to_s turns any object into a string.

You can customize to_s in your classes for clearer output.

It helps when printing, debugging, or combining objects with text.