Symbols
Often, when programming, you need to use the same string over and over. Perhaps the string is a key in a Hash, or maybe the string is the name of a method. In that case, you’d probably want the access to that string to be immutable so its value can’t change, and you’d also want accessing the string to be as fast and use as little memory as possible.
This brings us to Ruby’s symbols. Symbols aren’t exactly optimized strings, but for most purposes, you can think of them as special strings that are immutable, are only created once, and are fast to look up. Symbols are meant to be used as keys and identifiers, while strings are meant to be used for data.
A symbol literal starts with a colon and is followed by some kind of name:
| | walk( ... |
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access