In this section, we will learn how to convert objects of different types into Ruby String values.
How to convert a value into string in Ruby? (Ruby to_s Method)
When you pass a string value to methods like puts or print, they are passed to the output stream and you’ll see them on the terminal. This works because these two methods, for example, only work with string values.
But we can see that even other data types like an integer or boolean value appear on the output stream when we pass them to such methods!
This is because they have a method called to_s which will be called whenever we invoke a non-string value into an operation where string value is needed.
By default, any class you create in Ruby will inherit this method from a root class named `Object`. So when we invoke an object that is created from a user-made class in an operation where a string value is needed, Ruby will automatically call the to_s method of that object.
But the to_s method declared in the Object class might not have the appropriate value we look for when our object is invoked in string type operation.
So for this reason we can override the to_s method and define the specific string value we want to be returned when a string value is expected from the object.
Ruby to_s method Syntax:
The to_s method does not take an argument. Simply override the method in your class and it will be called automatically whenever your object is invoked in a string type operation.
Example: using Ruby to_s method in Ruby
class Person def to_s return "This is the person class" end end prs = Person.new puts prs
Output:
This is the person class
How does to_s method work in Ruby?
You can see that the to_s method is called when we passed the `prs` object into the puts method and so the value within the body of the overridden method `to_s` returned as a result.