On Wed, 20 Aug 2008, Jean Lazarou wrote:
I read some of the sample code (the clock one) and I don't understand how
some of field scoping happens, I mean I don't understand from a Ruby
point of view. Here is the code (simplified):
01 Shoes.app :height => 260, :width => 250 do
02 @radius, @centerx, @centery = 90, 126, 140
03 stack :margin => 10 do
04 animate(8) do
05 @time = Time.now
06 clear do
07 draw_background
08 stack do
09 background black
10 para @time.strftime("%a"),
11 ....
12 end
13 end
14 clock_hand @time.sec + (@time.usec * 0.000001),2,30,red
15 ...
16 end
17 end
18 def draw_background
19 ...
20 end
21 def clock_hand(time, sw, unit=30, color=black)
22 ...
23 end
24 end
So,
(1) the '@time' field is defined in the block starting at line 3 and is
visible in the inner block starting at line 8
Yes, that would agree with lexical scoping....
(2) the 'draw_background' method (could defined in the block starting at
line 1 using something like 'block.instance_eval(&block)') is also
Not sure what you are getting at with the
(could...'block.instance_eval(&block)')
visible in the inner blocks
Yes, the draw_background is a method of the application. Methods are
visible within other methods of the same class/object.
How does all this magic happen? Is it happening in the C code? Is it
Which magic? What is your expectation, and which things go against
it, so that it looks like magic? If you mean @time is visible in
line 14 when that is outside the lexical scope where it was defined,
then notice the "@" sign. In Ruby that means "instance variable",
part of the object and visible to everything inside the object.
Normally these are defined in the initialize method, but modules can
introduce them as well, so I'm not entirely sure of the limits on
where they can be called into existence within an object, so long as
they are created before they are read.
possible to play with blocks using pure Ruby?
Yes. Blocks, procs, and lambdas are all variations on the same thing.
They create new scope, but inheriting from the present scope, and they
allow you to give a method access to that scope by calling the block, or
yielding to it.
Thanks,
Jean Lazarou
HTH
Hugh