开发者

Question about ruby symbols [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicates:

Why don't more pr开发者_运维知识库ojects use Ruby Symbols instead of Strings?

What's the difference between a string and a symbol in Ruby?

I am new to ruby language. From what I read I must use symbols instead strings where is possible. Is that correct ?


You don't HAVE TO do anything. However, it is advisable to use symbols instead of strings in cases where you will be using the same string literal over and over again. The reason is that there is only ever 1 of the symbol held in memory, while if you use the string literal it will created anew whenever you assign it, therefore potentially wasting memory.


Strings are mutable where as Symbols are not. Symbols are better performance wise.

Read this article to better understand symbols, strings and their differences.


It's sort of up to you which one you use -- you can use a string anywhere you'd use a symbol, but not the other way around. Symbols do have a number of advantages, in a few cases.

Symbols give you a performance advantage because two symbols of the same name actually map to the same object in memory, whereas two strings with the same characters create different objects. Symbols are immutable and lightweight, which makes them ideal for elements that you won't be changing around at runtime; keys in a hash table, for example.

Here's a nice excerpt from the Ruby Newbie guide to symbols:

The granddaddy of all advantages is also the granddaddy of advantages: symbols can't be changed at runtime. If you need something that absolutely, positively must remain constant, and yet you don't want to use an identifier beginning with a capital letter (a constant), then symbols are what you need.

The big advantage of symbols is that they are immutable (can't be changed at runtime), and sometimes that's exactly what you want.

Sometimes that's exactly what you don't want. Most usage of strings requires manipulation -- something you can't do (at least directly) with symbols.

Another disadvantage of symbols is they don't have the String class's rich set of instance methods. The String class's instance method make life easier. Much easier.


Symbols have two main advantages:

  • They are like intern'ed strings, so they can improve performance.
  • They are syntactically distinct which can make your code more readable, particularly for programs that use hashtables as complex build-in data structures.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜