7stud -- wrote in post #990282:
> Josep M. Bach wrote in post #990178:
>> Hello,
>>
>> I think I don't agree/understand how instance variables work in ruby.
>>
>
> By rule, instance and global variables are initialized to nil by
> default, and local variables aren't

Local variables *are* initialized to nil.

But because Ruby doesn't require you to put parentheses after a method 
call - e.g. you can write 'puts' instead of 'puts()' - it needs a way to 
decide whether the bareword 'puts' is actually a local variable or a 
method call.

This is decided statically, when the code is being read in and parsed 
(but before it is run).

Within a particular scope (remember that 'class' and 'def' start a new 
scope), if an assignment to that word has been seen earlier, then that 
word is treated as a local variable.

Hence:

def foo
  puts = 123
  puts
end

returns 123 (and doesn't print anything), whereas

def foo
  puts
end

prints a blank line (and returns nil, which is the return value of the 
'puts' method)

> --but there is some local variable
> trickery here:
>
> if 1 > 5
>   x = 10
> end
>
> puts x  #nil

It doesn't matter whether the assignment is executed or not. The 
statement "x = 10" has been seen, and so from that point onwards a 
bareword "x" is treated as a local variable rather than a method.

If there is no assignment, then a method call is attempted:

puts y    # like puts(y()), tries to call method y

But if that fails, it could mean either that you forgot to define method 
'y', or that you forgot to assign to local variable 'y'. Hence the error 
message says:

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

Incidentaly, you can always force a method call using parentheses or 
send or dot notation:

  puts = 123
  puts          # returns 123
  puts()        # calls method
  send :puts    # calls method
  self.puts     # calls method (only if not private)
  puts(puts)    # prints 123 :-)

Regards,

Brian.

-- 
Posted via http://www.ruby-forum.com/.