Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Ruby expose symbols?

Tags:

symbols

ruby

Why does Ruby expose symbols for explicit use? Isn't that the sort of optimisation that's usually handled by the interpreter/compiler?

like image 390
Jerome Avatar asked Feb 21 '10 20:02

Jerome


2 Answers

Part of the issue is that Ruby strings are mutable. Since every string Ruby allocates must be independent (it can't cache short/common ones), it's convenient to have a Symbol type to let the programmer have what are essentially immutable, memory-efficient strings.

Also, they share many characteristics with enum's, but with less pain for the programmer.

like image 191
zenazn Avatar answered Sep 22 '22 15:09

zenazn


Ruby symbols are used in lieu of string constants in other similar languages. Besides the performance benefit, they can be used to semantically distinguish between string data and a more abstract symbol. Being syntactically different, they can clearly be distinguished in code.

like image 36
troelskn Avatar answered Sep 23 '22 15:09

troelskn