Why is local variable created in one branch of if statement available in the other?

  • Thread starter Alexey Verkhovsky
  • Start date
M

MenTaLguY

I find it hard to understand why this code prints nil instead of
saying "unknown method or local variable foo":

def hmm
if false
foo = 'quack'
else
p foo
end
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
 
C

ChrisH

I find it hard to understand why this code prints nil instead of
saying "unknown method or local variable foo":


def hmm
if false
foo = 'quack'
else
p foo
end
end

hmm> ruby hmm.rb

nil

Thoughts?

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
 
A

Alexey 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.

Thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,239
Messages
2,571,200
Members
47,840
Latest member
Tiffany471

Latest Threads

Top