What Is a Symbol in Ruby?

Find out what symbols are in Ruby

In Ruby, a symbol is an object that's an instance of the Symbol class:

:foo.class #=> Symbol

It can be created in two ways:

  1. Literal Form — by prefixing colon (:) to a word;
  2. Converting a string — by using either intern or to_sym method.
# symbol literal
my_symbol_1 = :foo
my_symbol_2 = :"foo bar"

puts my_symbol_1.class #=> Symbol
puts my_symbol_2.class #=> Symbol
# string -> symbol
my_symbol_1 = "foo bar".intern
my_symbol_2 = "foo bar".to_sym

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

Just like in real world, a Symbol is a representation for something. It exists as a unique name inside the ruby interpreter, that remains the same throughout the program execution (i.e. two symbols with the same name always refer to the same object), no matter the context. For example:

def Foo()
    puts :foo.object_id #=> 1234
end

puts :foo.object_id #=> 1234
puts :foo.object_id #=> 1234
Foo()

Ruby stores symbols in a symbol table (to guarantee/enforce uniqueness), and only creates a new Symbol if it does not already exist. You can see a list of all symbols by using the following command:

Symbol.all_symbols

A Symbol can be used to:

  • Represent a particular state of the program (or be used as an equivalent of enumerations);
  • Dynamically send messages to (or call methods on) objects;
  • Serve as keys of a hash map.

For example, you could represent state in your program like so:

# instead of:
if order_status == 0

# you could do:
if order_status == :pending

You could dynamically send messages to objects like so:

# instead of:
"foo,bar,baz".split(",") #=> ["foo", "bar", "baz"]

# you could dynamically invoke the method:
"foo,bar,baz".__send__(:split, ",") #=> ["foo", "bar", "baz"]

You could use symbols as keys in a hash map like so:

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

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

This is the same as the older "hash rocket" syntax:

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

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

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