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 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.
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