Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 516
Jakub Zak Avatar asked Dec 30 '14 15:12

Jakub Zak


3 Answers

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.

like image 188
Ghoti Avatar answered Sep 29 '22 07:09

Ghoti


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.

like image 34
Jörg W Mittag Avatar answered Sep 29 '22 08:09

Jörg W Mittag


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.

like image 43
Boris Stitnicky Avatar answered Sep 29 '22 08:09

Boris Stitnicky