Reputation: 13063
This question is supposed to be the reverse of this one: Why use symbols as hash keys in Ruby?
As you can see, everyone agrees that symbols are the most logical choice for hash keys. However, I'm building a web application with the sinatra framework, and the request
object is a hash that contains String
s as keys. Can anyone explain why this would be a design choice?
Upvotes: 2
Views: 1164
Reputation: 303271
Because the source of the keys--the query string--is made up of strings, so searching through this string for keys, it is most directly convenient to index the hash via the strings.
Every Symbol that is created in the Ruby runtime is allocated and never released. There is a theoretical (but unlikely) DOS attack available by sending hundreds of thousands of requests with unique query string parameters. If these were symbolized, each request would slowly grow the runtime memory pool.
Strings, on the other hand, may be garbage collected. Thousands of unique strings handled across various requests will eventually go away, with no long-term impact.
Edit: Note that with Sinatra, symbols are also available for accessing the params
hash. However, this is done by creating a hash that is indexed by strings, and converting symbols (in your code) to strings when you make a request. Unless you do something like the following:
params.each{ |key,_| key.to_sym }
...you are not at risk of any symbol pseudo-DOS attack.
Upvotes: 4