# Re: Global dynamic method definition

**URL:** <https://www.ruby-forum.com/t/re-global-dynamic-method-definition/75841>\
**Category:** Ruby\
**Created:** [November 13, 2006, 9:32pm UTC](https://www.ruby-forum.com/t/re-global-dynamic-method-definition/75841 "2006-11-13T21:32:29Z")\
**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:32pm UTC](https://www.ruby-forum.com/t/re-global-dynamic-method-definition/75841/1 "2006-11-13T21:32:29Z")

</div>

> I’m trying to code in Ruby something that looks like this,  
> when reduced and highly simplified:  
> [snip]  
> As the code suggest, what I except is:
> 
> B class init  
> B instance init  
> 123  
> 456  
> B instance init  
> 789

Depending on how much you’ve simplified it, you might see if the  
following code helps. (I wonder if you really need to dynamically define  
a new method; you certainly don’t to achieve the desired output of your  
sample.)

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  
end

def dynamic\_method  
self.class.dynamic\_method\_outputs.each do |v|  
puts v  
end  
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
