What Does a Colon Before a Variable Name Mean in Ruby?

In Ruby, a colon (:) before a word is used to create/use a Symbol object. For example:

my_symbol_1 = :foo
my_symbol_2 = :"foo bar"

puts my_symbol_1.class #=> Symbol
puts my_symbol_2.class #=> Symbol

Same is the case when creating a hash map using the (old) "hash rocket" (=>) syntax:

my_hash = { :a => "foo", :b => "bar" }

puts my_hash[:a] #=> "foo"
puts my_hash[:b] #=> "bar"

This syntax is called the literal form. It is one of the two ways in which you can create/use a Symbol.

A new symbol is only created if a Symbol by the same name does not already exist, otherwise the program will refer to the same object in memory (i.e. the existing Symbol object is used). This means that two symbols with the same name always refer to the same object.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.