Post-Condition if Statements And NameErrors

M

MaggotChild

I thought this was odd:

def bs
1
end

print y + 1 if y = bs

NameError: undefined local variable or method `y' for main:Object

And, of course, the multi-line if works:

if x = bs
print x + 1
end
 
E

Eric Christopherson

I thought this was odd:

def bs
=A01
end

=A0print y + 1 if y =3D bs

NameError: undefined local variable or method `y' for main:Object

And, of course, the multi-line if works:

if x =3D bs
=A0print x + 1
end

Something like this came up a few weeks ago. I think the parser is the
one generating the NameError, because the parser only consider a
variable to be defined if it sees an assignment to it, and such
assignment has to come *before* any use of the variable. Even though
the interpreter actually would actually execute y =3D bs first, the
parser doesn't see it at the point where its value is used.
 
B

Benoit Daloze

[Note: parts of this message were removed to make it a legal post.]
Something like this came up a few weeks ago. I think the parser is the
one generating the NameError, because the parser only consider a
variable to be defined if it sees an assignment to it, and such
assignment has to come *before* any use of the variable. Even though
the interpreter actually would actually execute y = bs first, the
parser doesn't see it at the point where its value is used.

Yeah, that's a bit annoying and considerably reduce while-one-liners
possibilities:

lines = IO.read('mac.txt').lines.to_a

puts line while line = lines.pop

but that works if you assign anything to line before ...
 

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
473,770
Messages
2,569,586
Members
45,085
Latest member
cryptooseoagencies

Latest Threads

Top