Symbols in Ruby | an introduction to the concept of immutable strings
I want to show you the more modern way of creating hashes in Ruby, but first I need to introduce you to a concept that does not exist in PHP in any shape or form. But don’t be scared, it’s really not that complicated.
So in your application, sometimes you have these strings that represent something in the system but not necessarily for our user’s to actually read. Sometimes we end up creating “machine level” strings that have an associated canoncial name:
$models = [
'hyundai' => 'Hyundai',
'land_rover' => 'Land Rover',
'rolls_royce' => 'Rolls Royce',
];
Now we have a machine level name called land_rover
that represents the common name “Land Rover”. Sometimes this serves as a pseudo-key to dynamically get the data we need.
Rubyists love this concept so much they built a dedicated structure in the language itself that encapsulates this idea. These “machine names” are called Symbols.
Practically speaking, you can think of Symbols as Strings that are unchangeable and usually represent something else.
Symbols can be stored in variables just like Strings can:
favorite_cheese = :muenster
Heck, they can even be turned back into Strings:
:muenster.to_s
'muenster'
Strings can also easily be converted into their respective Symbols with the .to_sym
method:
'muenster'.to_sym
:muenster
However, the Symbols in Ruby are immuatable. This is a fancy computer science term for saying that they cannot change.
Here’s an example of how Strings are mutable:
'swiss'.concat(' cheese')
=> 'swiss cheese'
We changed the String by concatinating another String called cheese to swiss.
However, Symbols don’t play around like that:
:havarti.concat(' cheese')
NoMethodError: undefined method `concat` for :havarti:Symbol
The above error message translated into English: ‘‘Hi I’m a Symbol, I don’t know what .concat
means at all. Because I can’t change from my original form.”