January 9 2020
Ruby Tip: Local Variables from Unexecuted Code
Recently, I had a bug where I reassigned params
in a Rails controller but only for development mode. However, when I pushed to production, I found params
would become nil after passing this unexecuted code.
As it turns out, this is a feature of Ruby: “The local variable is created when the parser encounters the assignment, not when the assignment occurs”. (Ruby documentation)
> x
NameError: undefined local variable or method `y` for main:Object
from (irb):3
from /Users/bdunagan/.rvm/rubies/ruby-2.2.5/bin/irb:11:in `<main>`
> x = 1 if false
=> nil
> x
=> nil
> p local_variables
[:x, :_]
=> [:x, :_]