tags:

views:

131

answers:

2

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?

+1  A: 

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.

clyfe
so the reason these projects aren't implementing this must be because it's not common knowledge, I can't think of anything else.
viatropos
considering the speed of the "rest" of ruby code, the sym optimization is kind of pointless, so the case is not lack of knowledge, but rather personal preference. rails uses it more for the aesthetics imho, nicer to type :x than "x"
clyfe
lol, it is nicer. but if something is more optimized, I think we should use it, especially if it's more fun to write.
viatropos
+2  A: 

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.

psyho
Internally Ruby symbols are stored as integers, so they are as big as integers are on your platform. Besides that - and also like integer literals - they are unique (there's never two 1 or :foo objects), so I wouldn't worry about GC too much.
Michael Kohl