Ruby provides two string conversion methods, `to_s` and `to_str`, that serve fundamentally different purposes. `to_s` is defined on virtually all objects and returns a string representation for display purposes — it's an explicit conversion. `to_str`, by contrast, is an implicit conversion that signals the object behaves like a string and can be used wherever a String is expected. Only the `String` class in Ruby core implements `to_str`. Defining `to_str` on a custom class enables implicit coercion, for example allowing concatenation with `+` without explicit casting. The same distinction applies to analogous method pairs like `to_int`/`to_i`, `to_ary`/`to_a`, and others.

5m read timeFrom marcgg.com
Post cover image
Table of contents
Difference In Scope Of DefinitionDifference In BehaviorNote On Implicit / Explicit ConversionSumming It Up

Sort: