官术网_书友最值得收藏!

Symbols

Symbols look like variables, however, with a colon (:) prefixed. For example, :symbol_1. Symbols need not be predeclared and assigned a value. Ruby guarantees that the symbol has a particular value, no matter where it appears in a Ruby program.

Symbols are very useful because a given symbol name refers to the same object throughout a Ruby program. Two strings with the same content are two different objects; however, for a given name, there can only be one single symbol object. Let's examine the following example to illustrate this fact:

irb
2.1-head :001 > puts "string".object_id
70168328185680
 => nil
2.1-head :002 > puts "string".object_id
70168328173400
 => nil
2.1-head :003 > puts :symbol.object_id
394888
 => nil
2.1-head :004 > puts :symbol.object_id
394888
nil

As you can see, we started by creating a string object with the string value and sought its object ID using the object_id method. Next, we tried the same thing once more. In both the cases, we received different object IDs. However, when we applied the same concept to a symbol object called :symbol, we received the same object ID both the times.

Ruby uses a symbol table to hold the list of symbols. Symbols, like variables, are names—names of instances, variables, methods, and classes. So, let's say we had a method called method1; this would automatically create a symbol called :method1 in the symbol table. This symbol table is maintained at all the times while the program is under execution. To find what is present in this symbol table, you can execute the Symbol.all_symbols method.

Symbols are more effective than strings as they get initialized just once. Let's see an example.

Let's call the following code snippet as Code1:

day = "Sunday"
if day == "Sunday"
  puts "Holiday!"
else
  puts "Work day"
end

Let's call the following code snippet as Code2:

day = :Sunday
if day == :Sunday
  puts "Holiday!"
else
  puts "Work day"
end

In Code1, we've a Sunday string. It's used once to be assigned to a variable called day and, the next time, we use this string for comparison. In this case, two instances of string objects are created in memory. However, in Code2, we've a symbol called :Sunday and it's declared just once. All later references to the symbol refer to the same old object.

With this knowledge of symbols, a question arises as to when to use symbols and when to make use of strings. There is no easy answer to this, but as a general practice:

  • If the content of the object is important, a string is a more apt choice
  • If the identity of the object is important, a symbol is a more suitable choice
主站蜘蛛池模板: 忻州市| 临安市| 汾阳市| 正镶白旗| 浦城县| 广宁县| 元朗区| 南涧| 建昌县| 商河县| 手游| 芒康县| 石城县| 农安县| 景东| 通城县| 洪洞县| 会昌县| 宜丰县| 原平市| 黔东| 永登县| 铁岭县| 宁国市| 定结县| 桦川县| 吉安市| 信阳市| 台山市| 新龙县| 沐川县| 贵定县| 垫江县| 翁源县| 丹阳市| 曲沃县| 金昌市| 永丰县| 威远县| 南通市| 桂阳县|