What is the difference between a symbol and a variable in Ruby? [duplicate] What is the difference between a symbol and a variable in Ruby? [duplicate] ruby ruby

What is the difference between a symbol and a variable in Ruby? [duplicate]


A symbol is an "internalized" string, it's more like a constant than anything. Typical example:

account_details = {  :name => 'Bob',  :age => 20}

Here the symbols :name and :age are keys for a hash. They are not to be confused with variables. account_details is a variable.

A variable in Ruby is a handle to an object of some sort, and that object may be a symbol.

Normally you employ symbols when using strings would result in a lot of repetition. Keep in mind that strings are generally distinct objects where a distinct symbol always refers to the same object, making them more efficient if used frequently.

Compare:

"string".object_id == "string".object_id# => false:string.object_id == :string.object_id# => true

Even though those two strings are identical, they're independent string objects. When used as keys for hashes, arguments to methods, and other common cases, these objects will quickly clutter up your memory with massive amounts of duplication unless you go out of your way to use the same string instance. Symbols do this for you automatically.


Variables hold a reference to an object. For example, variables can reference strings and symbols like:

a = 'foo'b = :bar

In Ruby string are mutable, it means that you can change them: 'foo' + 'bar' will give a concatenated string. You can perceive symbols as immutable strings, it means that you cannot change a symbol: :foo + :bar will give you an error. Most importantly, the same symbols hold reference to the same object:

a = :foob = :fooa.object_id # => 538728b.object_id # => 538728

This increases performance in hash lookups and other operations.


They're pretty different. Variables give a label to an object. Symbols are more like strings, except that they're immutable and interned in memory, so that multiple references to the same symbol don't use extra memory. (Contrast this with strings, where multiple references to the same string of characters will result in multiple copies of the string.)