3

I see this answer in various websites:

If the contents (the sequence of characters) of the object are important, use a string If the identity of the object is important, use a symbol

But, what does this actually mean? Please give me an explanation which even a layman can understand.

Esh
  • 685
  • 1
  • 5
  • 9
  • 1
    Possible duplicate of [What's the difference between a string and a symbol in Ruby?](http://stackoverflow.com/questions/255078/whats-the-difference-between-a-string-and-a-symbol-in-ruby) – max pleaner Jan 13 '17 at 06:41
  • 1
    symbols are nice for hash keys because there's a concise syntax. They're also used in metaprogramming, and many functions require symbol arguments. Other than that, it really doesn't matter. – max pleaner Jan 13 '17 at 06:43
  • Also this: http://stackoverflow.com/questions/11447537/using-ruby-symbols/11447568#11447568 – Sergio Tulentsev Jan 13 '17 at 06:46
  • See also http://stackoverflow.com/q/41516232 – akuhn Jan 13 '17 at 08:40

1 Answers1

5
a = :foo
b = :foo

a and b refer to the same object in memory (same identity)

a.object_id # => 898908
b.object_id # => 898908

Strings behave differently

a = 'foo'
b = 'foo'

a.object_id # => 70127643805220
b.object_id # => 70127643805200

So, you use strings to store data and perform manipulations on data (replace characters or whatnot) and you use symbols to name things (keys in a hash or something). Also see this answer for more use cases for symbol.

Community
  • 1
  • 1
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
  • 2
    It's also important to *not* use symbols when you're dealing with user supplied data, like arbitrary JSON keys or parameter names. In older versions of Ruby these were never garbage collected and presented a Denial of Service attack surface. Using symbols for frequently repeated things that you control is a good idea. They're also faster to compare. – tadman Jan 13 '17 at 06:59