SoWhat
SoWhat

Reputation: 5622

Why use the :"string val" notation to declare a symbol

:"String Val" creates a symbol that stores "String Val". :"Hello Kitty".class returns Symbol. I imagine this is to create a symbol that has spaces. I can't think of any reasons why this would be useful except methods that force require symbols.

Is there any other reason to use this?

Upvotes: 0

Views: 102

Answers (4)

sawa
sawa

Reputation: 168199

There is already String#to_sym. Given this fact, it may seem that :"..." is a syntax sugar that can always be replaced by String#to_sym. But that is actually not the case. Besides for the convenience of the programmer, there has to be a notation :"..." irrespective of the existence of String#to_sym, at least for inspection. In this example,

"foo bar".to_sym
# => :"foo bar"

the inspection form cannot be "foo bar".to_sym, which expresses application of a method to a string, because the same object can be obtained in many other ways, and that is just one way to create such object. There has to be a unique way to express such symbol, which is :"foo bar".

Once we have such expression for inspection, it is natural that that expression can also be used as a symbol literal.

Upvotes: 2

ndnenkov
ndnenkov

Reputation: 36110

It's not just spaces, it's any gibberish that would otherwise be considered something that should be interpreted. Like

:"zoo@-55**12 +foo(3, baz)[7] - ❤️"

Quotes mean "use as is". Which makes them intuitive as literal syntax for strings, but you can see that there are other uses.


But saying "just" methods that require symbols instead of strings is a bit misleading. Despite what Rails tries to make you believe, symbols and strings are very different and should be treated differently. Symbols are usually used as a sort of magical constants, while strings are regular values.

It's like saying why do we need String#to_i. Is it just for methods that treat 42 and "42" differently?


As for why there is literal syntax for it - just convenience (like any other syntax sugar). Consider:

{
  something_something:            1,
  something_completely_different: 2,
  'yet something else':           3,
}

It would be unfortunate if we had to write:

{
  :something_something            => 1,
  :something_completely_different => 2,
  'yet something else'.to_sym     => 3,
}

Or

{
  something_something:            1,
  something_completely_different: 2,
  'yet something else'.to_sym =>  3,
}

Upvotes: 2

Bartosz Pietraszko
Bartosz Pietraszko

Reputation: 1407

Important reason for that is to utilize string interpolation, which allows symbols to be dynamically generated.

5.times.map{ |x| :"symbol_#{x}" }
=> [:symbol_0, :symbol_1, :symbol_2, :symbol_3, :symbol_4]

Upvotes: 3

sawa
sawa

Reputation: 168199

Here is another use case:

:3
# => syntax error, unexpected tINTEGER, expecting tSTRING_CONTENT or tSTRING_DBEG or tSTRING_DVAR or tSTRING_END

:"3"
# => :"3"

Upvotes: 1

Related Questions