![]() Prev |
![]() Contents |
![]() Next |
Ruby user's guide | Local variables |
A local variable has a name starting with a lower case letter or an
underscore character (_
). Local variables do
not, like globals and instance variables, have the value
nil
before initialization:
ruby> $foo nil ruby> @foo nil ruby> foo ERR: (eval):1: undefined local variable or method `foo' for main(Object) |
The first assignment you make to a local variable acts something like a declaration. If you refer to an uninitialized local variable, the ruby interpreter thinks of it as an attempt to invoke a method of that name; hence the error message you see above.
Generally, the scope of a local variable is one of
proc{
... }
loop{
... }
def
... end
class
... end
module
... end
In the next example, defined?
is an operator which checks
whether an identifier is defined. It returns a description of the
identifier if it is defined, or nil
otherwise. As you see,
bar
's scope is local to the loop; when the loop exits, bar
is undefined.
ruby> foo = 44; print foo, "\n"; defined? foo 44 "local-variable" ruby> loop{bar=45; print bar, "\n"; break}; defined? bar 45 nil |
Procedure objects that live in the same scope share whatever local
variables also belong to that scope. Here, the local variable
bar
is shared by main
and the procedure objects
p1
and p2
:
ruby> bar=0 0 ruby> p1 = proc{|n| bar=n} #<Proc:0x8deb0> ruby> p2 = proc{bar} #<Proc:0x8dce8> ruby> p1.call(5) 5 ru |