Matthew Rathbone
Matthew Rathbone

Reputation: 8269

What are the negatives of adding a to_str method to Symbol?

I'm working in a ruby app in which symbols are used in various places where one would usually use strings or enums in other languages (to specify configurations mostly).

So my question is, why should I not add a to_str method to symbol?

It seems seems sensible, as it allows implicit conversion between symbol and string. So I can do stuff like this without having to worry about calling :symbol.to_s:

File.join(:something, "something_else") # => "something/something_else"

The negative is the same as the positive, it implicitly converts symbols to strings, which can be REALLY confusing if it causes an obscure bug, but given how symbols are generally used, I'm not sure if this is a valid concern.

Any thoughts?

Upvotes: 4

Views: 324

Answers (3)

m_x
m_x

Reputation: 12564

when an object does respond_to? :to_str, you expect him to really act like a String. This means it should implement all of String's methods, so you could potentially break some code relying on this.

to_s means that you get a string representation of your object, that's why so many objects implement it - but the string you get is far from being 'semantically' equivalent to your object ( an_hash.to_s is far from being a Hash ). :symbol.to_str's absence reflects this : a symbol is NOT and MUST NOT be confused with a string in Ruby, because they serve totally different purposes.

You wouldn't think about adding to_str to an Int, right ? Yet an Int has a lot of common with a symbol : each one of them is unique. When you have a symbol, you expect it to be unique and immutable as well.

Upvotes: 2

Dave Newton
Dave Newton

Reputation: 160261

The negative is what you say--at one point, anyway, some core Ruby had different behavior based on symbol/string. I don't know if that's still the case. The threat alone makes me a little twitchy, but I don't have a solid technical reason at this point. I guess the thought of making a symbol more string-like just makes me nervous.

Upvotes: 1

axsuul
axsuul

Reputation: 7480

You don't have to implicitly convert it right? Because doing something like this will automatically coerce it to a string.

"#{:something}/something_else"  # "something/something_else"

Upvotes: 2

Related Questions