sawa
sawa

Reputation: 168199

Symbol literal or a method

Are :"foo" and :'foo' notations with quotations a symbol literal, or is : a unary operator on a string?

Upvotes: 0

Views: 205

Answers (3)

Arup Rakshit
Arup Rakshit

Reputation: 118289

Ruby's documentation on Symbol literals says this:

You may reference a symbol using a colon: :my_symbol.

You may also create symbols by interpolation:

:"my_symbol1"
:"my_symbol#{1 + 1}"

Basically :"foo" and :'foo' are symbol literals, but they are useful when you want to create symbols using interpolation.

Upvotes: 1

Konrad Reiche
Konrad Reiche

Reputation: 29513

: is really just part of the literal you enter yourself or create through a method. Although : can take a name or a "string" to create a literal, unlike an operator it does not provoke any action or modify a value.

In each case an instance of Symbol is returned. Writing : with string notation is sometimes important. If you want to represent, for instance, a string containg whitespace as a symbol you need to use the string notation.

> :foo
=> :foo 

> :foo bar
SyntaxError: (irb):2: syntax error, unexpected tIDENTIFIER, expecting end-of-input

> :"foo bar"
=> :"foo bar"

Furthermore, it is interesting to explore this with the equality operator (==)

> :"foo" == :foo
=> true 

> :"foo " == :foo
=> false

My advice, do not think of it as passing a string or name to create a symbol, but of different ways to express the same symbol. In the end what you enter is interpreted to an object. This can be achieved in different ways.

> :"foo"
=> :foo

After all, %w(foo bar) is also an alternative way of writing ['foo', 'bar'].

Upvotes: 3

7stud
7stud

Reputation: 48609

You also need quotes if your symbol has spaces:

hash = {
  :"a b c" => 10,
  :"x y z" => 20,
}

puts hash[:"a b c"]

--output:--
10

So the first one. From the docs:

[Symbols] are generated using the :name and :"name" literals syntax, and by the various to_sym methods.

Upvotes: -1

Related Questions