# Post-Condition if Statements And NameErrors

**URL:** <https://www.ruby-forum.com/t/post-condition-if-statements-and-nameerrors/186127>\
**Category:** Ruby\
**Created:** [March 31, 2010, 11:06pm UTC](https://www.ruby-forum.com/t/post-condition-if-statements-and-nameerrors/186127 "2010-03-31T23:06:03Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![MaggotChild](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/7ea924/32.png) [@MaggotChild](https://www.ruby-forum.com/u/MaggotChild)\
**Post date:** [March 31, 2010, 11:06pm UTC](https://www.ruby-forum.com/t/post-condition-if-statements-and-nameerrors/186127/1 "2010-03-31T23:06:03Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![MaggotChild](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/7ea924/32.png) [@MaggotChild](https://www.ruby-forum.com/u/MaggotChild)\
**Post date:** [April 1, 2010, 1:50am UTC](https://www.ruby-forum.com/t/post-condition-if-statements-and-nameerrors/186127/2 "2010-04-01T01:50:35Z")

</div>

On Wed, Mar 31, 2010 at 4:05 PM, MaggotChild [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
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.

---

<div class="post-metadata">

**Author:** ![MaggotChild](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/7ea924/32.png) [@MaggotChild](https://www.ruby-forum.com/u/MaggotChild)\
**Post date:** [April 1, 2010, 6:22pm UTC](https://www.ruby-forum.com/t/post-condition-if-statements-and-nameerrors/186127/3 "2010-04-01T18:22:38Z")

</div>

> 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 …
