Forum: Ruby Why is local variable created in one branch of if statement

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
38a02bf7121a81be5be6f3d488ce23b5?d=identicon&s=25 Alexey Verkhovsky (Guest)
on 2007-04-05 19:50
(Received via mailing list)
I find it hard to understand why this code prints nil  instead of
saying "unknown method or local variable foo":

> cat hmm.rb
def hmm
  if false
    foo = 'quack'
  else
    p foo
  end
end

hmm
> ruby hmm.rb
nil

Thoughts?
912c61d9da47754de7039f4271334a9f?d=identicon&s=25 MenTaLguY (Guest)
on 2007-04-05 20:04
(Received via mailing list)
On Fri, 6 Apr 2007 02:49:27 +0900, "Alexey Verkhovsky"
<alexey.verkhovsky@gmail.com> wrote:
> end
The decision on whether foo is a method or a variable is made by the
parser as it walks through the body of the function, rather than when
the function is executed.  By default, foo is considered a method, but
once it encounters foo = somewhere, it considers foo to be a variable
for the remainder of the function.

So, by the time the parser processes the else branch of the if
statement, it has already seen an assignment in the earlier if branch,
and therefore interprets 'foo' as a variable name rather than a method
call.

-mental
23172b6630dc631a134c9bad2fec2a39?d=identicon&s=25 ChrisH (Guest)
on 2007-04-05 20:11
(Received via mailing list)
On Apr 5, 1:49 pm, "Alexey Verkhovsky" <alexey.verkhov...@gmail.com>
wrote:
>   end
> end
>
> hmm> ruby hmm.rb
>
> nil
>
> Thoughts?
>
> --
> Alex Verkhovsky

The variable 'foo' is created during parsing stage so exists as "foo =
'quack'" has been parsed.
Execution then results in the assignment being skipped so foo has the
default nil value.

Cheers
Chris
38a02bf7121a81be5be6f3d488ce23b5?d=identicon&s=25 Alexey Verkhovsky (Guest)
on 2007-04-05 20:54
(Received via mailing list)
> The variable 'foo' is created during parsing stage so exists as "foo =
> 'quack'" has been parsed.
> Execution then results in the assignment being skipped so foo has the
> default nil value.

Thanks.
This topic is locked and can not be replied to.