Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symbols in Ruby

Tags:

symbols

ruby

I don't know if I understand what a symbol is. I read the following in different places:

  • Symbols are immutable, meaning that the content won't change after they are initialized. This means that the object can have many references to it since the content can't change.
  • Use Symbols for identity and strings where content matters.
  • Symbol object are only instantiated once, and exists as long as the process runs.
  • About symbol table

I do not understand these phrases. Last, I don't understand what a symbol object is. Is :name a symbol object, or is :namejust a reference to a symbol object somewhere else?

like image 761
Yoko Sumoki Avatar asked Dec 27 '22 17:12

Yoko Sumoki


1 Answers

This quote from the book 'Eloquent Ruby' helped me understand symbols, there's a whole chapter in the book dealing with strings and symbols that is also very good.

The answer is that we tend to use strings of characters in our code for two rather dif- ferent purposes: The first, and most obvious, use for strings is to hold some data that we are processing. Read in those Book objects from the database and you will very likely have your hands full of string data, things like the title of the book, the author’s name, and the actual text.

The second way that we use strings of characters is to represent things in our pro- grams, things like wanting to find all of the records in a table. The key thing about :all in our Book ActiveRecord example is that ActiveRecord can recognize it when it sees it—the code needs to know which records to return, and :all is the flag that says it should return every one. The nice thing about using something like :all for this kind of “stands for” duty is that it also makes sense to the humans: You are a lot more likely to recognize what :all means when you come across it than 0, or -1, or even (heaven forbid!) 0x29ef.

These two uses for strings of characters—for regular data processing tasks on the one hand and for internal, symbolic, marker-type jobs on the other—make very dif- ferent demands on the objects. If you are processing data, you will want to have the whole range of string manipulation tools at your fingertips: You might want the first ten characters of the title, or you might want to get its length or see whether it matches some regular expression. On the other hand, if you are using some characters to stand for something in your code, you probably are not very interested in messing with the actual characters. Instead, in this second case you just need to know whether this thing is the flag that tells you to find all the records or just the first record. Mainly, when you want some characters to stand for something, you simply need to know if this is the same as that, quickly and reliably.
like image 179
ipr101 Avatar answered Jan 13 '23 00:01

ipr101