Rails options, why the syntax is params [: key]?

I'm trying to manually create some parameters to go to the Rails controller function, why the params hash keys are listed with a colon, for example. params[:key]but not params["key"]?

+5
source share
3 answers

Rails uses ActiveSupportsHashWithIndifferentAccess for almost all hashes that come from within, for example params. A HashWithIndifferentAccessbehaves just like a regular hash, except for accessing keys by character, or a string of the same "value" returns the same value of the hash function. For instance:

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

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

against. normal hash:

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

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

This allows you not to worry (for better or for worse) about whether a particular key was a character or string.

+16

, , . , ( , ). . HashWithIndifferentAccess #to_sym.

0

( ) ( ) - Rails. Hash , . Ruby 1.9 .

0

All Articles