assign/replace params hash in rails

后端 未结 1 447
梦毁少年i
梦毁少年i 2020-12-10 07:16

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 e

相关标签:
1条回答
  • 2020-12-10 07:50

    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.

    0 讨论(0)
提交回复
热议问题