- Mastering Chef
- Mayank Joshi
- 448字
- 2021-07-16 14:02:24
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