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

I work in a ruby ​​application in which characters are used in different places where strings or enumerations in other languages ​​are usually used (to basically indicate configurations).

So my question is: why should I not add the to_str method to the character?

Seems to seem reasonable as it allows for implicit conversion between character and string. Therefore, I can do such things without worrying about calling: symbol.to_s:

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

The negation is the same as the positive, it implicitly converts the characters to strings, which can be REALLY confusing if it causes an incomprehensible error, but given how characters are usually used, I'm not sure if this is a real problem.

Any thoughts?

+4
source share
3 answers

when does the object execute respond_to? :to_str respond_to? :to_str , you expect it to actually act as a String . This means that it must implement all String methods, so you can potentially interrupt some code by relying on it.

to_s means you get a string representation of your object, 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 Hash ). :symbol.to_str absence reflects this: the symbol should NOT and should NOT be confused with a string in Ruby, because they serve completely different purposes.

You would not think about adding to_str to Int, right? However, Int has a lot to do with the symbol: each one is unique. When you have a symbol, you expect it to be unique and unchanging.

+2
source

You do not need to implicitly convert it correctly? Because doing something like this automatically forces it to a string.

 "#{:something}/something_else" # "something/something_else" 
+2
source

Denial is what you say - at some point, anyway, some Ruby core had a different character / line based behavior. I don’t know if this is so. The threat alone twitches me slightly, but at the moment I have no solid technical reason. I think the idea of ​​making a symbol more like a string just makes me nervous.

+1
source

Source: https://habr.com/ru/post/1380298/


All Articles