# Re: best way to dynamically create new instance methods

**URL:** <https://www.ruby-forum.com/t/re-best-way-to-dynamically-create-new-instance-methods/79050>\
**Category:** Ruby\
**Created:** [December 11, 2006, 9:41pm UTC](https://www.ruby-forum.com/t/re-best-way-to-dynamically-create-new-instance-methods/79050 "2006-12-11T21:41:46Z")\
**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:** [December 11, 2006, 9:41pm UTC](https://www.ruby-forum.com/t/re-best-way-to-dynamically-create-new-instance-methods/79050/1 "2006-12-11T21:41:46Z")

</div>

From: Dan T.

> Sent: Monday, December 11, 2006 1:28 PM  
> To: ruby-talk ML  
> Subject: best way to dynamically create new instance methods  
> [snip]  
> What I want create\_method() to do (simplified here) is, given the  
> argument “baz”, add a method to the current instance of Foo that would  
> look like this if it were a traditional method (that is, not  
> dynamically  
> created):

Assuming that you want each instance of foo to have its own list of  
methods:

class Foo  
def initialize( \*method\_names )  
method\_names.each{ |meth\_name|  
create\_method( meth\_name )  
}  
end

def create\_method( meth\_name )  
( class \<\< self; self; end ).class\_eval{  
define\_method( meth\_name ){ |\*args|  
args[0]  
}  
}  
end  
end

f1 = Foo.new( :bar, ‘baz’ )  
p f1.bar( ‘a’, ‘b’, ‘c’ )  
#=\> “a”

f2 = Foo.new( ‘whee’ )  
p f2.whee( ‘yahoo’ )  
#=\> “yahoo”

p f2.bar  
#=\> undefined method `bar’ for #Foo:0x2833f90 (NoMethodError)
