# Global dynamic method definition

**URL:** <https://www.ruby-forum.com/t/global-dynamic-method-definition/75836>\
**Category:** Ruby\
**Created:** [November 13, 2006, 8:18pm UTC](https://www.ruby-forum.com/t/global-dynamic-method-definition/75836 "2006-11-13T20:18:04Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![philpraxis](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/77aa72/32.png) [@philpraxis](https://www.ruby-forum.com/u/philpraxis)\
**Post date:** [November 13, 2006, 8:18pm UTC](https://www.ruby-forum.com/t/global-dynamic-method-definition/75836/1 "2006-11-13T20:18:04Z")

</div>

Hi,

I’m trying to code in Ruby something that looks like this, when reduced  
and highly simplified:

* * *

class B  
puts “B class init”  
@@dynamic\_method\_outputs = Array.new

def initialize  
puts “B instance init”  
end

def B.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

The output of this is:

B class init  
B instance init  
123  
456  
B instance init  
123  
456  
789

As the code suggest, what I except is:

B class init  
B instance init  
123  
456  
B instance init  
789

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

The only trick I could find for the moment is to use a dummy  
instanciation, but it is still not really clean, and prone to errors.

* * *

class B  
puts “B class init”  
@@dynamic\_method\_outputs = Array.new

def initialize  
puts “B instance init”  
@@dynamic\_method\_outputs.clear  
end

def B.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  
D1.new

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

d1 = D1.new  
d1.dynamic\_method

## d2 = D2.new d2.dynamic\_method 789

Output is here:

B class init  
B instance init  
B instance init  
B instance init  
123  
456  
B instance init  
789

Does anyone have a better idea?

Philippe
