It's fairly common for people learning Ruby to not quite understand symbols. A symbol is a standard Ruby type, just like other built in Ruby types. Here is an example of how a symbol is just an object that is of a certain type:
'A'.class # => String
1.class # => Fixnum
:a.class # => Symbol
As with any other type, symbols have methods. If you open IRB and type :a.methods.sort
it will show you all the methods you can call on a symbol. E.g., :a.to_s # => 'a'
As you've noticed, symbols are often used as Hash
keys. However, other types can also be Hash
keys:
my_hash = { 'A' => 'an A', 1 => 'a 1', :a => 'the symbol a'}
my_hash['A'] # => 'an A'
my_hash[1] # => 'a 1'
my_hash[:a] # => 'the symbol a'
Just like you can pass a String
or other types to a method, you can pass a Symbol
. In fact, in the last example, we are passing a String
, a Fixnum
, and then a Symbol
to my_hash
's []
method.
The reason people really like symbols for hash keys is that they are very lightweight to reuse. Here is an example showing one of the main differences between a symbol and any other object:
"a".object_id # => 70098399407740
"a".object_id # => 70098399393460
"a".object_id # => 70098399388140
:a.object_id # => 359368
:a.object_id # => 359368
:a.object_id # => 359368
As you can see, I create three strings that have the value "a", and they each have a different object id. In other words, there are three String
objects in memory that contain the value "a". In contrast, every time I use :a
it has the same object id. There is only one :a
object in my entire program.
It's not uncommon to pass symbols to methods. You'll see this a lot in Rails.