Rails parameters, why the params[:key] syntax?

ruby, ruby-on-rails, ruby-on-rails-3

Solution

Rails uses ActiveSupport’s `HashWithIndifferentAccess` for almost all hashes that come from within itself, such as `params`. A `HashWithIndifferentAccess` behaves the same as a regular hash except key access by symbol or string of the same “value” returns the same hash value. For example:

h = HashWithIndifferentAccess.new
h[:foo] = 'bar'
h[:foo]  #=> "bar"
h['foo'] #=> "bar"

h['foo'] = 'BAR'
h[:foo]  #=> "BAR"

vs. a normal hash:

h = {}
h[:foo] = 'bar'
h[:foo]  #=> "bar"
h['foo'] #=> nil

h['foo'] = 'BAR'
h[:foo]  #=> "bar"

This allows you to not have to worry (for better or worse) about whether a particular key was a Symbol or a String.

Problem

I'm trying to manually create some params to pass to a Rails controller function, why are keys to the params hash listed with the colon, e.g. `params[:key]` and not `params["key"]`?

Original source