What is the difference between to_s and inspect?
Last updated
to_s produces a human-readable string for display, while inspect produces a developer-facing, debug-oriented representation that ideally shows the object's internal state.
to_sis for users: Used by string interpolation andputs; meant to be clean and readable.inspectis for developers: Used byp, the IRB/console, and arrays printed withp; shows quotes, structure, ivars.Concrete differences:
"hi".to_sishi, but"hi".inspectis"hi"(with quotes);nil.to_sis empty whilenil.inspectis"nil".Override both for your classes: Default
inspectlists instance variables; a custom one makes debugging much clearer.
- https://railsatscale.com/2024-04-30-fixing-a-footgun-in-activerecord-core-inspect/
- https://docs.ruby-lang.org/en/3.1/Object.html
- https://ruby-doc.org/core/Object.html
- https://www.reddit.com/r/ruby/comments/2qeg2f/whats_the_difference_between_to_s_and_inspect_as/
- https://goodspace.ai/interview-questions/ruby
- https://medium.com/rubycademy/display-complex-objects-d897be936ae0
- https://medium.com/the-magic-pantry/rubys-inspect-considered-harmful-24d5716c78c2