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

Learn what a colon before a variable means 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.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.