RFS: Symbols - 007

Symbols are immutable data structure in ruby, it can come in handy in many instances. We also explore the difference between ruby's Strings and Symbols in this episode.

Let's begin by creating a symbol. You'll notice below that symbols are prefixed with a colon :

something = :something

We can also create symbols via strings.

name = "zack"my_sym = :"#{name}"=> :zack

Ruby Strings vs Symbols

So what's the difference between strings and symbols? When should we choose to use one over the other?

Symbols are immutable which mean they can't be modified or changed. If you need to represent something that does not change it's always better to use symbols. Ruby will not create a new instance of a symbol if they are the same. Ruby will however always create a new instance of a string even if they are the same.

name = "zack"=> "zack"name_2 = "zack"=> "zack"name.object_id=> 70348129853700name_2.object_id=> 70348129862380

We can see that ruby created 2 objects for the same string. Let's try the same thing with symbols

my_sym = :zack=> :zackmy_sym_2 = :zack=> :zackmy_sym.object_id=> 1516828my_sym_2.object_id=> 1516828

We can see that ruby referenced the same object when it came to symbols.

Symbols are great for representing things that don't change for example the name of an attribute. Let's say for example we are trying to describe a person, a person has a :name and :age the actual name of the person might be "zack" and the age might be 34 but the attribute :name will never change so we would use symbols to represent the name of the attribute.

{:name => "zack", :age => 34}# can also be represented as {name: "zack", age: 34}

That's it! have a read through the documentation to see what can be done with Symbols!