Ruby Symbols: Explained

Image Source: knowtebook.com
Many programmers old and new to ruby alike, get confused when they see Ruby symbols, sometimes or all the time. It will take a lot of getting used to, before you ever do this smoothly. A lot of us came to know about the Ruby language through Ruby on Rails projects. In Ruby on Rails, symbols are everywhere. I mean everywhere. So it is important to note and memorize the concept of symbols in Ruby.
A symbol in Ruby is an instance of the class Symbol. A symbol is defined by prefixing a colon with an identifier like “:name”, “:id” or “:user”. The Symbol class in Ruby contains one class method:
- all_symbols and instance methods id2name, inspect, to_i, to_int, to_s and to_sym.
- all_symbols – returns an array of all the symbols in Ruby’s symbol table.
- id2name – returns the string representation of the symbol,:name.id2name returns “name”.
- inspect – returns the symbol literally
- to_i – returns an integer unique for each symbol
- to_int – same as to_i
- to_s – same as id2name
- to_sym – converts the symbol to a symbol.