On Sat, Feb 8, 2014 at 9:57 AM, Edoardo Rossi <edd.rossi / gmail.com> wrote:

> Hi Arup.
>
> If you run your snippet with debugging on (-d) you will see a warning
> about an unused variable...
> For example:
>

Your example doesn't show such a warning.


>
> # foo_bar.rb
>
> foo = 1
> puts foo
> puts "foo is 1" if foo == 1
> puts "bar is 1" if bar != 1
>
> # => Exception `NameError' at foo_bar.rb:6 - undefined local variable
> or method `bar' for main:Object
>
> if() when used as a modifier has its own context... its scope.
> So the assignment is never seen outside of the if and 'bar' it's undefined.
>

I believe this is incorrect and sows confusion. In reality, the reason `puts
a if a = 0.zero?` fails if a hasn't been defined is because the parser
scans strictly from left to right looking for assignments. When it finds an
assignment, it considers the left side of that assignment to be a valid
variable from there to the end of the scope. It doesn't backtrack into the
portion of the line before a modifier-if, so `puts a` is unable to resolve
the variable a.


>
> This works:
>
> if (bar = 1+1) == 2
>   puts "bar is 2? yup! (#{bar})"
> end
>
> because the block that the if statement takes is also within the same
> scope as the assignment.
> .
> Hope it helps
>
> On Sat, Feb 8, 2014 at 4:30 PM, Arup Rakshit <lists / ruby-forum.com> wrote:
> > Look the below code
> >
> > (arup~>~)$ pry --simple-prompt
> >>> x = 1
> > => 1
> >>> puts "x is 1" if x == 1
> > x is 1
> > => nil
> >>> puts "x is 1" if x != 1
> > => nil
> >
> > The above code is telling, first checking the conditions, then execute
> > the body `puts ...`. I agree this, why then error from the below code ?
> >
> >>> puts a if a = 0.zero?
> > NameError: undefined local variable or method `a' for main:Object
> > from (pry):4:in `__pry__'
> >
> > --
> > Posted via http://www.ruby-forum.com/.
>
>
>
> --
>
>
> Eddie
>