Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assign/replace params hash in rails

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.

like image 525
eugen Avatar asked Aug 26 '09 16:08

eugen


1 Answers

The params which contains the request parameters is actually a method call which returns a hash containing the parameters. Your params = line is assigning to a local variable called params.

After the if false block, Ruby has seen the local params variable so when you refer to params later in the method the local variable has precedence over calling the method of the same name. However because your params = assignment is within an if false block the local variable is never assigned a value so the local variable is nil.

If you attempt to refer to a local variable before assigning to it you will get a NameError:

irb(main):001:0> baz
NameError: undefined local variable or method `baz' for main:Object
        from (irb):1

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.

irb(main):007:0> baz = "Example" if false
=> nil
irb(main):008:0> baz
=> nil

See: Assignment - Local Variables and Methods in the Ruby docs.

like image 127
mikej Avatar answered Oct 26 '22 13:10

mikej