According to some sources you must do this yes.
The symbols are stored internally in a table as integers without signal, which saves a lot of memory compared to the use of strings. As a result, the comparison between symbols is much faster.
Another advantage is that symbols are immutable, while strings can have content altered and "break" somehow the hash.
But there are always side effects.
One is that the symbols are not collected and will reside "eternally" in the interpreter’s table.
The impact will be small if you use only explicit symbols in the code. However, if you use the function to_sym
to get the symbols corresponding to many different strings, especially if these strings have external origin, the use of permanently allocated memory can increase considerably.
Specifically talking about the example of the question, the excerpts hash = {:indice => 'valor'}
and hash = {indice: 'valor'}
are equivalent, the first was used in Ruby until version 1.8 and the second was introduced in Ruby 1.9.
In the links you passed is different from what I asked. In the links they compare
{'a' => 'b'} vs {:a => 'b'}
and I want to know about{a: 'b'} vs {:a => 'b'}
.– user7261
@user3153542 Truth. I replied to title question and I didn’t exactly notice your example. I’ve already added the explanation in the answer.
– utluiz