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"]
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With