I was setting up symbols in my code like:
"name_of_symbol".to_sym
However, my principal engineer picked it up during code review as a bad practice and asked me to set symbols like:
:"name_of_symbol"
When I asked him why? He said it's bad practice, but when I asked for what reason he just said it is, which is not really a satisfying answer. So how is it? Is there any difference at all?
The colon indicates a symbol. I wouldn't call it bad practice so much as unconventional practice, which might make the code a little harder to understand.
I know that :"Some weird stuff"
is legal but don't like it, personally I'd rather use :Some_weird_stuff
and leave the quotes out all together - using quotes when you don't need to is just adding noise - I'm very anti-noise. Noise is bad practice, it makes understanding take longer.
Sometimes, when you're matching things that came in as strings but for consistency you want symbols then you don't have much choice, but I prefer not to have to ask this question, FWIW.
When you have syntactically clean symbols you can use the
{ thing: "value" }
syntax, which is a joy and very clear and uncluttered.
Interestingly, though:
irb
> class String ; def to_sym ; puts "bob" ; end ; end
=> nil
> "fred".to_sym
bob
=> nil
> :"fred"
=> :fred
So Boris' point is a valid one.
One is a Symbol
literal, the other is a String
literal upon which you call a method.
Personally, I find it weird to write a String
when you mean to write a Symbol
, only to then immediately convert the String
into a Symbol
. Why not write a Symbol
in the first place? That makes your intentions much clearer.
Other answers argue correctly that :"foo bar"
is superior to "foo bar".to_sym
because it is clearer, better expresses your intention, is more readable, faster etc. But there is one more reason: "foo bar".to_sym
relies on String#to_sym
method, and there is a possibility (although remote) that this method might be redefined. This is the one non-cosmetic reason why :"foo bar"
is in principle better practice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With