Is overriding to_s methods in Ruby bad? [closed]
No, you should feel free to override to_s
- there are no ill side-effects. As long as your new to_s
is more informative than the built-in (not exactly a high standard there), you're in the clear.
And they help make your test failures read better - sometimes by a lot - which is never a bad thing. Go for it!
I override to_s
all the time in my Rails project:
def to_s first_name + " " + last_name end
so that it's easier to show objects in the view:
<%= @person %>
It might be tricky to do that because sometimes, inspect
method just calls to_s
, and if that is altered, you might have trouble debugging. If you think altering to_s
may confuse you when you need to see the results by methods that rely on inspect
, such as p
, then maybe you need to redefine inspect
for that class at the same time. As long as you are sure what you are doing, you might want to do it.