Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't more projects use Ruby Symbols instead of Strings?

Tags:

symbols

ruby

When I first started reading about and learning ruby, I read something about the power of ruby symbols over strings: symbols are stored in memory only once, while strings are stored in memory once per string, even if they are the same.

For instance: Rails' params Hash in the Controller has a bunch of keys as symbols:

params[:id] or
params[:title]...

But other decently sized projects such as Sinatra and Jekyll don't do that:

Jekyll:

post.data["title"] or
post.data["tags"]...

Sinatra:

params["id"] or
params["title"]...

This makes reading new code a little tricky, and makes it hard to transfer code around and to figure out why using symbols isn't working. There are many more examples of this and it's kind of confusing. Should we or shouldn't we be using symbols in this case? What are the advantages of symbols and should we be using them here?

like image 823
Lance Avatar asked Mar 10 '10 09:03

Lance


2 Answers

In ruby, after creating the AST, each symbol is represented as a unique integer. Having symbols as hash keys makes the computing a lot faster, as the main operation is comparison.

like image 130
clyfe Avatar answered Oct 24 '22 08:10

clyfe


Symbols are not garbage collected AFAIK, so that might be a thing to watch out for, but except for that they really are great as hash keys.

like image 37
psyho Avatar answered Oct 24 '22 09:10

psyho