1

I noticed a strange behavior with Ruby local variables in the code below. It seems that Ruby runs into the false part and sets params to nil. The code in irb is below:

2.1.2 :001 > def params
2.1.2 :002?>   {a:1}
2.1.2 :003?> end
2.1.2 :014 > def go1!
2.1.2 :015?>   p params
2.1.2 :016?>   if false
2.1.2 :017?>     params = 1
2.1.2 :018?>   end
2.1.2 :019?>   p params
2.1.2 :020?> end
 => :go1! 
2.1.2 :021 > go1!
{:a=>1}
nil
 => nil

Can anyone explain this?

Ajedi32
  • 45,670
  • 22
  • 127
  • 172
Spec
  • 415
  • 1
  • 5
  • 10

1 Answers1

3

Ruby determines the lifetime of local variables while it parses the code, so even if params = 1 assignment wouldn't be reached, params will be interpreted as local variable (and set to nil by default) in this scope.

Here's the link to documentation:

http://docs.ruby-lang.org/en/2.1.0/syntax/assignment_rdoc.html#label-Local+Variables+and+Methods

Marek Lipka
  • 50,622
  • 7
  • 87
  • 91
  • But shouldn't be not treated as a local variable if params is already available. – Jikku Jose Dec 23 '14 at 10:56
  • 1
    thanks for you link, my friend also give me a more detail explain. see https://ruby-hacking-guide.github.io/syntree.html on local Variable Part. – Spec Dec 23 '14 at 11:20