[ruby-talk:00353] Re: local variables

From: gotoken@... (GOTO Kentaro)
Date: 1999-05-27 09:50:33 UTC
List: ruby-talk #353
Hi, 

In message "[ruby-talk:00351] local variables"
    on 99/05/27, Pros Yeboah <yeboah@tu-harburg.de> writes:
>Can someone  please explain it ,why I get this:
>ruby -e'i=3;def foo;p defined?(i);end;foo'  #==>nil
>ruby -e'i=3;1.times{p defined?(i)}             #==>"local-variable"

	There are four kinds of scope for local variable: 
	  * BEGIN
	  * top level
	  * def/class/module...end
	  * block

	BEGIN, top level, and def/class/module...end have new scopes apart
	from outer scope.  Matz said this policy originated in CLU. 
	On the other hand, only the block scope can nest.  So, as you get:

>ruby -e'i=3;1.times{p defined?(i)}             #==>"local-variable"

	Note the case of a local variable which first appears in a block;
	Such variable can NOT be referred from other blocks.  For example, 
	the following code doesn't work because secondary appearance of foo
	is in another scope which does NOT share the first loop block. 

def bar
  loop do
    foo = 1
    break
  end
  loop do
    p foo
    break
  end
end

bar # NameError at `p foo'


	(Acknowledgment: The above is based on Nahi's summary about the 
	scope of local variables.)


	By the way, a tricky tuneup are known.  See the result of a simple 
	benchmark (UNIX `time' command is used). 

% time ruby -e        '1000000.times{|i| f = i}'
3.372u 0.000s 0:03.40 99.1%     504+668k 0+6io 0pf+0w
% time ruby -e 'i = 0; 1000000.times{|i| f = i}'
2.593u 0.007s 0:02.62 98.8%     507+670k 0+6io 0pf+0w
%

	This result shows the fact that the first appearance of a variable 
	spends more time cost.  But this result depends on the 
	implementation of interpreter. 


	Now, the following is also frequently asked question, which is
	related to the above tuneup. 

	Q: Why did I get the below?

% ruby -e '2.times{p defined?(i); i = nil}'
false
false
%

	A: The block introduces its own bindings every time. 
	   It is because of that the second evaulation prints false in 
	   spite of i = nil in the first evaulation. 


Well, I (also) think the block scope little complex,,, but I have no
idea to make better. 

-- gotoken

In This Thread