Hi Arup.

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

# 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.

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