String & Symbol in Ruby

Juzer Shakir
3 min readJul 3, 2021

--

A glimpse into their behavior at runtime.

String

Any data encapsulated within “ ” or ‘ ’, is a string.

“like this”

‘or like this’

Symbol

A symbol is an unique identifier that is code and not data! Its prefixed with a colon ‘:’ and contains no space in-between.

:like_this

Mutable and Immutable

An object is mutable if it can be modified, and immutable if it cannot.

Checking mutability of both a string and a symbol
"Hello World"
mutable_immutable.rb:7:in `<main>': undefined method `<<' for :Hello:Symbol (NoMethodError)
Did you mean? <

From the above program, we can conclude that string is a mutable object where its value can be changed and modified, whereas a symbol is an immutable object where its value cannot be modified within the program.

The immutability nature of a symbol makes them useful in programming as this makes their initiation and comparison faster than that of mutable objects. Mutable objects might cause bugs that are sometimes difficult to detect.

Memory

Each time we run ruby code it takes up a little bit of memory space in the computer. At a program runtime, when an object is created, it gets assigned an ID, and it's stored in a memory. To check this in action, ruby provides a method called .object_id which returns the ID of an object.

Even though the string is identical, it takes up different memory space each time we use it in the program. Having to allocate and de-allocate strings increases the execution time. Imagine using this similar logic in a large application, where it would make your application slow, buggy, and inefficient!

While for a symbol, the story is different. every time a symbol is initiated it becomes an instance of a Symbol class. Identical symbol names with the same object type refer to the same object in memory. Hence, no matter how many times you call it, it will refer to a single place in the memory where its located. This saves code execution time, uses less memory, and makes code more efficient.

How do you choose the right object type?

If the sequence of the characters or display of a text or an ability to update value later in program is important, use strings.

If an identity of an object is important, use symbol.

Fun Fact

Ruby maintains a table called global_symbols to hold all the symbols initiated in a program. This includes names of instance variables, methods, classes, hashes, struct, etc. So for example, if there’s a method called method_test in a program, Ruby will automatically create a corresponding symbol for it named as :method_test. We can find the list of all the symbols available in our program by calling Symbol.all_symbols.

Any suggestions or edits in this article are always welcome! Thank You!

My previous article: Block, Proc & Lambda
My next article: A Class in Ruby

GitHub | LinkedIn

--

--