|
| 1 | +# About |
| 2 | + |
| 3 | +[Symbols][symbols] are named identifiers that can be used to refer to a value. |
| 4 | +Symbols are created through a symbol literal, which is by prefixing a name with a `:` character, e.g. `:foo`. |
| 5 | +They also allow for being written with quotes, e.g. `:"foo"`, which allows, for example, spaces in the name. |
| 6 | + |
| 7 | +```ruby |
| 8 | +:foo # => :foo |
| 9 | +:"foo boo" # => :"foo boo" |
| 10 | +``` |
| 11 | + |
| 12 | +Symbols are used in many places in the language, including as keys in hashes, to represent method names and variable names. |
| 13 | + |
| 14 | +## Identifier |
| 15 | + |
| 16 | +What makes symbols different from strings is that they are identifiers, and do not represent data or text. |
| 17 | +This means that two symbols with the same name are always the same object. |
| 18 | + |
| 19 | +```ruby |
| 20 | +"foo".object_id # => 60 |
| 21 | +"foo".object_id # => 80 |
| 22 | +:foo.object_id # => 1086748 |
| 23 | +:foo.object_id # => 1086748 |
| 24 | +``` |
| 25 | + |
| 26 | +## Modifying Symbols |
| 27 | + |
| 28 | +Symbols are immutable, which means that they cannot be modified. |
| 29 | +This means that when you "modify" a symbol, you are actually creating a new symbol. |
| 30 | +There are a few methods that can be used to manipulate symbols, they all return new symbols. |
| 31 | +All methods can be found in the [Symbol API][symbols-api]. |
| 32 | + |
| 33 | +```ruby |
| 34 | +:foo.upcase # => :FOO |
| 35 | + |
| 36 | +:foo.object_id # => 1086748 |
| 37 | +:foo.upcase.object_id # => 60 |
| 38 | +``` |
| 39 | + |
| 40 | +The benefit of symbols being immutable is that they are more memory efficient than strings, but also safer to use as identifiers. |
| 41 | + |
| 42 | +## Conversion |
| 43 | + |
| 44 | +Symbols can be converted to strings and vice versa. |
| 45 | +This can be useful when you want to modify a symbol, or when you want to use a symbol as a string. |
| 46 | +To present a string as a symbol, you can use the `String#to_sym` method, and to do the opposite, you can use the `Symbol#to_s` method. |
| 47 | +Due to symbols having a limited set of methods, it can be useful to convert a symbol to a string to use string methods on it, if a new symbol is needed. |
| 48 | + |
| 49 | +```ruby |
| 50 | +:foo.to_s # => "foo" |
| 51 | +"foo".to_sym # => :foo |
| 52 | +``` |
| 53 | + |
| 54 | +[symbols]: https://www.rubyguides.com/2018/02/ruby-symbols/ |
| 55 | +[symbols-api]: https://rubyapi.org/o/symbol |
0 commit comments