Is overriding to_s methods in Ruby bad?

Ruby

Ruby Problem Overview


I've been experimenting and find that I like redefining Object's to_s methods.

Is this a bad idea or is it good practice?

Ruby Solutions


Solution 1 - Ruby

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!

Solution 2 - Ruby

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 %>

Solution 3 - Ruby

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.

Solution 4 - Ruby

It's not "bad" per se, but it isn't "good" either. It really depends on the context.

If you are doing this for a one-shot place (for example inside your rails app's /lib/ folder, for a particular app) it is probably alright (make sure to give the file a descriptive name, such as object_to_s_patch.rb or similar, and that all patches are on the same place)

If you are doing a gem or a lib, on the other hand, I would not override it. Instead I'd add another method - Object.to_special_s or something. But I'd also try not to touch Object if possible - If you can get by with using YourModule::to_s(object) that'd be probably even better.

The reasoning behind this is that other people might be using Object.to_s for other stuff, maybe in other libs. Monkeypatching it will produce clashes with those other libs.

The only exception when doing a gem that I can think of is when the main point (or one of the main points) of that library is actually overriding the method; in other words, you are literally making a lib that overrides Object.to_s, and little else. I'd put some big warning on the documentation on that case. This way people using it will not get surprised.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionfivetwentysixView Question on Stackoverflow
Solution 1 - RubyMagnarView Answer on Stackoverflow
Solution 2 - RubyDGMView Answer on Stackoverflow
Solution 3 - RubysawaView Answer on Stackoverflow
Solution 4 - RubykikitoView Answer on Stackoverflow