7.4. Built-in and custom to_* (conversion) methods
Ruby offers a number of built-in methods whose names consist of to_ plus an indicator of a class to which the method converts an object: to_s (to string), to_sym (to symbol), to_a (to array), to_i (to integer), and to_f (to float). Not all objects respond to all of these methods. But many objects respond to a lot of them, and the principle is consistent enough to warrant looking at them collectively.
7.4.1. String conversion: to_s
The most commonly used to_ method is probably to_s. Every Ruby object—except instances of BasicObject—responds to to_s, and thus has a way of displaying itself as a string. What to_s does, as the following irb excerpts show, ranges from nothing more than return its ...
Get The Well-Grounded Rubyist, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.