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

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
主站蜘蛛池模板: 宝应县| 承德市| 忻州市| 平陆县| 抚顺市| 盈江县| 南开区| 建阳市| 碌曲县| 托里县| 唐海县| 建昌县| 池州市| 施甸县| 合作市| 吉木萨尔县| 黄山市| 南安市| 溧阳市| 遂宁市| 喜德县| 琼海市| 鲁山县| 福州市| 大洼县| 西青区| 梅州市| 霍林郭勒市| 岱山县| 博客| 连平县| 共和县| 云和县| 凤山县| 澄江县| 来凤县| 余江县| 财经| 巴南区| 准格尔旗| 方山县|