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?
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?
On Fri, 6 Apr 2007 02:49:27 +0900, “Alexey V.”
[email protected] 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
On Apr 5, 1:49 pm, “Alexey V.” [email protected]
wrote:
end
endhmm> 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
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 forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs