Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"]?

like image 767
fred basset Avatar asked Jan 27 '13 21:01

fred basset


1 Answers

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.

like image 73
Andrew Marshall Avatar answered Sep 19 '22 18:09

Andrew Marshall