[[Rails-core] Strange behavior with session]

Hi,

when I create the following method inside a controller which has sessions enabled, the result I get ("nil") is not the one I am expecting (CGI::Session). Has anybody an explanation for this strange behavior?

--- code   def strange     if nil       raise "strange"       session = "whatever"     end     render :text => session.inspect   end

when I create the following method inside a controller which has sessions enabled, the result I get (“nil”) is not the one I am expecting (CGI::Session). Has anybody an explanation for this strange behavior?

— code def strange if nil raise “strange” session = “whatever” end render :text => session.inspect end

This is a Ruby quirk. It ‘sees’ the local variable even if it’s never assigned when the program executes. For example:

a NameError: undefined local variable or method `a’ for #Object:0x2aaaaab232e0 from (irb):1 if false; a = 1 end => nil a => nil

jeremy

Hi Jeremy,

thanks for your answer.

Because in this ambiguous situation you may be assigning a local variable or you may be calling a writer method. Ruby interprets it as assigning a local variable.

jeremy