Jakub Zak
Jakub Zak

Reputation: 1232

Ruby symbol setup

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?

Upvotes: 6

Views: 146

Answers (4)

Ghoti
Ghoti

Reputation: 2380

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.

Upvotes: 6

Boris Stitnicky
Boris Stitnicky

Reputation: 12578

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.

Upvotes: 3

benjaminjosephw
benjaminjosephw

Reputation: 4417

This seems like a matter of preference but I can see how writing a symbol as a symbol is a lot clearer than writing a string that you're changing into a symbol.

Also, the quote marks are unnecessary when you're using snake_case.

  1. "name_of_symbol".to_sym
  2. :"name_of_symbol"
  3. :name_of_symbol

This is a matter of style but it seems to me that 3 is the most readable and concise version of the three. If "best practice" means easy to read and therefore maintain, I'd say 3 wins.

Upvotes: 2

Jörg W Mittag
Jörg W Mittag

Reputation: 369428

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.

Upvotes: 4

Related Questions