| Start |
|---|
| Creating a Symbol The most common way to create a Here are some alternative ways to define a Symbols also have a The While some interesting symbols ( Symbols may end with a single Note that all of these different methods of creating symbols will return the same object: Since Ruby 2.0 there is a shortcut for creating an array of symbols from words: |
| Converting a String to Symbol Given a there are several ways to convert it to a |
| Converting a Symbol to String Given a The simplest way to convert it to a Another way to do it is by using the Syntax
RemarksAdvantages of using symbols over strings:1. A Ruby symbol is an object with O(1) comparison To compare two strings, we potentially need to look at every character. For two strings of length N, this will require N+1 comparisons But since every appearance of :foobar refers to the same object, we can compare symbols by looking at object IDs. We can do this with a single comparison.(O(1)) 2. A Ruby symbol is a label in a free-form enumeration In C++, we can use “enumerations” to represent families of related constants: But because Ruby is a dynamic language, we don’t worry about declaring a BugStatus type, or keeping track of the legal values. Instead, we represent the enumeration values as symbols: 3. A Ruby symbol is a constant, unique name In Ruby, we can change the contents of a string: But we can’t change the contents of a symbol: 4. A Ruby symbol is the keyword for a keyword argument When passing keyword arguments to a Ruby function, we specify the keywords using symbols: 5. A Ruby symbol is an excellent choice for a hash key Typically, we’ll use symbols to represent the keys of a hash table: |
Read Article
https://develop.horje.com/learn/1434/reference