# Re: Global dynamic method definition

**URL:** <https://www.ruby-forum.com/t/re-global-dynamic-method-definition/75842>\
**Category:** Ruby\
**Created:** [November 13, 2006, 9:30pm UTC](https://www.ruby-forum.com/t/re-global-dynamic-method-definition/75842 "2006-11-13T21:30:28Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![phrogz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/2acd7d/32.png) [@phrogz](https://www.ruby-forum.com/u/phrogz)\
**Post date:** [November 13, 2006, 9:30pm UTC](https://www.ruby-forum.com/t/re-global-dynamic-method-definition/75842/1 "2006-11-13T21:30:28Z")

</div>

From: Philippe L. [[mailto:removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)]

> In other words, the global @@dynamic\_method\_outputs is not  
> cleared between D1 and D2 class definitions.

Class variables are shared between a class and all its subclasses. You  
want an instance variable of the class itself:

class B  
puts “B class init”  
def self.dynamic\_method\_outputs  
@dynamic\_method\_outputs ||= []  
end

def initialize  
puts “B instance init”  
end

def self.add\_to\_dynamic\_method\_output(val)  
dynamic\_method\_outputs \<\< val

```
method_def = "def dynamic_method() "

dynamic_method_outputs.each do |v|
  method_def << "puts #{v} \n"
end

method_def << "end"

self.class_eval method_def

```

end  
end

class D1 \< B  
add\_to\_dynamic\_method\_output 123  
add\_to\_dynamic\_method\_output 456  
end

class D2 \< B  
add\_to\_dynamic\_method\_output 789  
end

d1 = D1.new  
d1.dynamic\_method

d2 = D2.new  
d2.dynamic\_method

#=\> B class init  
#=\> B instance init  
#=\> 123  
#=\> 456  
#=\> B instance init  
#=\> 789
