DEV Community

Lucas Barret
Lucas Barret

Posted on

Semiology in Ruby (What are Ruby Symbols) ?

Ruby Symbols

I have come to appreciate the power and versatility of symbols in the language. In this guide, I will provide a comprehensive overview of symbols in Ruby, including their definition, usage, and best practices.

Understanding Symbols in Ruby

In Ruby, a symbol is a class that is primarily used as an identifier. Although symbols may resemble strings and can be converted to them, they are not the same. Unlike strings, symbols are immutable and unique, making them ideal for use as method names, instance variable names, and keys in hashes.

Immortal vs. Mortal Symbols

What you need to understand is that symbols are unique. And once they are created you will call the same one after.
Before Ruby 2.2 Symbols were not Garbage Collected at all, after 2.2 it leads to the creation of 2 kind of symbols :

  • Immortal Symbols

  • Mortal Symbols

Mortal Symbols

Mortal symbols were first introduced after version 2.2 of Ruby, and they are automatically garbage collected once they are no longer in use.
There are several ways to create symbols in Ruby, including the following:

#Called to_sym on a Strings
"mortal_symbol".to_sym
#Use Symbols literals
:"another_mortal_sym"
#Use interpolation this give => :mortal_sym2
:"mortal_sym#{1+1}" 
Enter fullscreen mode Exit fullscreen mode

Immortal Symbols

Immortal symbols are the original type of symbols in Ruby, and they are not garbage collected.So, it is important be careful when using them in order to prevent memory leaks. There are several ways to create immortal symbols in Ruby :

#define a method dynamically with define_method
define_method(:immortal_method_sym) { puts "I am immortal" }
#define a instance variable with set_instance_variable
Object.instance_variable_set(:@a, "myvalue")
#creating a const using const_set
Object.const_set("MY_CONST","VALUE")

Enter fullscreen mode Exit fullscreen mode

Conclusion

In conclusion, symbols are an essential feature of the Ruby programming language that can greatly enhance the readability and performance of your code. By understanding the difference between immortal and mortal symbols and following best practices, you can use symbols to their full potential in your Ruby projects.

PS : Why I call this article " Semiology in Ruby " ?
Semiology is the study of signs and symbols in a language and it really cool isn't it ?

Top comments (0)