On 05.04.2007 12:37, gga wrote:
> Here's a simple snippet of code of a ruby scope pitfall (bug?) that I
> keep stumbling upon.
> Here a "global" function is invoked in two different contexts and
> returns different behavior due to self being set differently.
> 
> ---
> #!/usr/bin/env ruby
> 
> @x = 'hello global'
> 
> def global_func
>   puts "global_func: class:#{self.class} x=#@x"
> end
> 
> class A
>   def test_scope
>     global_func
>   end
> end
> 
> global_func
> 
> a = A.new
> a.test_scope
> ---
> 
> I'm wondering if this is intended behavior in the language.

It is intended:

13:16:34 [Temp]: ./scope.rb
#<Method: Object#global_func>
global_func: class:Object x=hello global
global_func: class:A x=
13:16:50 [Temp]: cat scope.rb
#!/usr/bin/env ruby

@x = 'hello global'

def global_func
   puts "global_func: class:#{self.class} x=#@x"
end

p method( :global_func )

class A
   def test_scope
     global_func
   end
end

global_func

a = A.new
a.test_scope
13:16:53 [Temp]:

Every top level method is defined in class Object and thus inherited by 
all classes.

 > If
> intended, what's the best approach to avoid running into this?  I'm
> currently porting code from other languages with different (more
> correct to me) scoping, and this keeps tripping me.

Do not use instance variables in global *functions*.  As simple as that.

Regards

	robert