Post-Condition if Statements And NameErrors

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

On Wed, Mar 31, 2010 at 4:05 PM, MaggotChild [email protected]
wrote:

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

if x = bs
print 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 = bs first, the
parser doesn’t see it at the point where its value is used.

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 …

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs