Customizing the Ruby Symbol

I set up the characters in my code, for example:

"name_of_symbol".to_sym 

However, my chief engineer took it during the code check as bad practice and asked me to install symbols such as:

 :"name_of_symbol" 

When I asked him why? He said that it was bad practice, but when I asked why he had just said that it was really not a satisfactory answer. So how is it? Is there any difference at all?

+6
source share
4 answers

Other answers correctly state that :"foo bar" superior to "foo bar".to_sym because it is more clear, better expresses your intention, more readable, faster, etc. But there is another reason: "foo bar".to_sym relies on the String#to_sym , and there is a possibility (albeit remote) that this method can be overridden. This is one non-cosmetic reason why :"foo bar" in principle, better suited.

+3
source

A colon indicates a character. I would not call it bad practice as well as unconventional practice, which could make the code a little more difficult to understand.

I know that :"Some weird stuff" is legal, but he doesn’t like it, personally I would prefer to use :Some_weird_stuff and leave the quotes all together - using quotes when you don’t just need to add noise - I am very anti-noise. Noise is bad practice, so understanding takes more time.

Sometimes, when you match things that go into strings, but for consistency you want to use characters, you don't have much choice, but I prefer not to ask this question, FWIW.

When you have syntactically pure characters, you can use

 { thing: "value" } 

syntax that is joy and very clear and uncluttered.

Interestingly, however:

 irb > class String ; def to_sym ; puts "bob" ; end ; end => nil > "fred".to_sym bob => nil > :"fred" => :fred 

Boris point is valid.

+6
source

One is the Symbol literal, the other is the String literal to which you call the method.

Personally, it seems strange to me to write String when you want to write Symbol to immediately convert String to Symbol . Why not write Symbol first? It makes your intentions clearer.

+4
source

This seems like a preference, but I see how to write a character as a character is much clearer than writing a string that you change into a character.

Also, quotation marks are not needed if you use snake_case.

  • "name_of_symbol".to_sym
  • :"name_of_symbol"
  • :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 support, I would say 3 wins.

+2
source

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


All Articles