Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.ruby > #2097
| From | Brian Candler <b.candler@pobox.com> |
|---|---|
| Newsgroups | comp.lang.ruby |
| Subject | Re: Dereferencing instance variables vs local variables/methods |
| Date | 2011-04-01 03:32 -0500 |
| Organization | Service de news de lacave.net |
| Message-ID | <bc855c03736707d0fd9012781f330818@ruby-forum.com> (permalink) |
| References | <25602497.1108.1301569887795.JavaMail.geo-discussion-forums@yqod3> <16fbe2a770a1e51f487325430816ecab@ruby-forum.com> |
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/.
Back to comp.lang.ruby | Previous | Next — Previous in thread | Find similar | Unroll thread
Re: Dereferencing instance variables vs local variables/methods 7stud -- <bbxx789_05ss@yahoo.com> - 2011-03-31 19:17 -0500 Re: Dereferencing instance variables vs local variables/methods Brian Candler <b.candler@pobox.com> - 2011-04-01 03:32 -0500
csiph-web