Prev - DUP - Next - TOC

Local varables


Local variables are specified by a name which is prepended with lower case letter or `_'. Let's see the following example.

 ruby> foo
 ERR: undefined local variable or method `foo' for main(Object)

What!? I got an error!!

The fact is that local variables need to be initialized by substitution differently from other type of variables, because the first substitution works similarly to declaration. When an undefined local variable are referred, it is regarded as an invoking of method without any arguments. So you got the error message, `undefined local variable or method'.

But you don't need to substitute arguments of a method in any definitions for methods, because their variables are considered as not yet being substituted.

The scope of a local variable is

A local variable in an iterator block is effective only in the block if it is substituted in the block for the first time.

 ruby> i0 = 1; print i0, "\n"; defined? i0
 1
 "local-variable"
 ruby> loop{i1=5; print i1, "\n"; break}; defined? i1
 5
 FALSE

In the above, `defined?' is an operator which checks whether its argument is defined or not. As you see, a variable `i1' that is substituted in loop for the first time is undefined after exiting the loop.

Procedure objects sharing their scope share also local variables.

 ruby> i=0
 0
 ruby> p1 = proc{|n| i=n}
 #<Proc:0x8deb0>
 ruby> p2 = proc{i}
 #<Proc:0x8dce8>
 ruby> p1.call(5)
 5
 ruby> i
 5
 ruby> p2.call
 5

A peculiar point to procedure objects is that sharing local scope is continued out of the scope. So, the local variable `i' is shared even if `p1' and `p2' are passed to outside of the scope (In this case, `i' can be access from `p1' or `p2'). See the followings:

 ruby> def foo
 ruby|   i = 15
 ruby|   get = proc{i}
 ruby|   set = proc{|n| i = n}
 ruby|   return get, set
 ruby| end
 ruby> p1, p2 = foo
 #<Proc>, #<Proc>
 ruby> p1.call
 15
 ruby> p2.call(2)
 2
 ruby> p1.call
 2

Prev - DUP - Next - TOC