I have the code sequence below in a rails controller action. Before the IF, params contains the request parameters, as expected. After it, params is nil. Can anyone please explain what is happening here?
if false
params = {:user => {:name => "user", :comment => 'comment'}}
end
Thank you.
The
paramswhich contains the request parameters is actually a method call which returns a hash containing the parameters. Yourparams =line is assigning to a local variable calledparams.After the
if falseblock, Ruby has seen the localparamsvariable so when you refer toparamslater in the method the local variable has precedence over calling the method of the same name. However because yourparams =assignment is within anif falseblock the local variable is never assigned a value so the local variable isnil.If you attempt to refer to a local variable before assigning to it you will get a NameError:
However if there is an assignment to the variable which isn’t in the code execution path then Ruby has created the local variable but its value is
nil.See: Assignment – Local Variables and Methods in the Ruby docs.