Symbols vs. variable

  • Thread starter Abder-rahman Ali
  • Start date
A

Abder-rahman Ali

What is the main difference between using a symbol (begins with :), and
a variable?

When should we use one over another?

Thanks.
 
J

Jesús Gabriel y Galán

What is the main difference between using a symbol (begins with :), and
a variable?

They are two completely different concepts:

- A symbol is an object. It's literal representation is a set of
characters that start with :, but it's a full object with methods,
etc. It has some properties that make them different to other objects,
the most relevant one being that all instances of the literal refer to
the same object:

irb(main):003:0> :test.object_id
=> 87218
irb(main):004:0> :test.object_id
=> 87218

Compare this to, for example, Strings or Arrays:

irb(main):005:0> "test".object_id
=> -610207318
irb(main):006:0> "test".object_id
=> -610213628
irb(main):007:0> [].object_id
=> -610222448
irb(main):008:0> [].object_id
=> -610232888


- A variable is a reference to an object. When you say

a = <some object>

you are creating a local variable that refers to <some object>. That
object could be any object, for example a Symbol:

a = :test
When should we use one over another?

I don't think this question has any sense, as they are completely
different concepts.

Jesus.
 
J

Jeremy Heiler

2010/7/7 Jes=FAs Gabriel y Gal=E1n said:
I don't think this question has any sense, as they are completely
different concepts.

A better question would be: Why use a symbol? Although, a quick Google
search will give some good answers.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,148
Messages
2,570,838
Members
47,385
Latest member
Joneswilliam01

Latest Threads

Top