How to Use the to_s Method in Ruby

09/20/2021
Contents
In this article, you will learn how to use the to_s method in Ruby.
The to_s Method
In Ruby, the to_s method is used to convert an object to a string representation. Here are some ways to use the to_s method in Ruby:
Convert a number to a string:
number = 42
string = number.to_s
Convert an array to a string:
array = [1, 2, 3]
string = array.to_s
Convert a hash to a string:
hash = {a: 1, b: 2, c: 3}
string = hash.to_s
Override the to_s method in a custom class:
class Person
attr_reader :name, :age
def initialize(name, age)
@name = name
@age = age
end
def to_s
"#{name} (#{age})"
end
end
person = Person.new("John", 30)
string = person.to_s
In the above example, we define a custom to_s method in the Person class to provide a string representation of the object. We then create a new Person object and call the to_s method on it to convert it to a string.