# Dynamically creating class methods

**URL:** <https://www.ruby-forum.com/t/dynamically-creating-class-methods/171351>\
**Category:** Ruby\
**Created:** [June 30, 2009, 11:27pm UTC](https://www.ruby-forum.com/t/dynamically-creating-class-methods/171351 "2009-06-30T23:27:33Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![sshaikh](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/b77776/32.png) [@sshaikh](https://www.ruby-forum.com/u/sshaikh)\
**Post date:** [June 30, 2009, 11:27pm UTC](https://www.ruby-forum.com/t/dynamically-creating-class-methods/171351/1 "2009-06-30T23:27:33Z")

</div>

I want to create a class method which allows us to create further class  
methods, so something like:

class Test  
class \<\< self  
def create\_method(name, proc)  
self.class.send(:define\_method, name, proc)  
end  
end  
end

proc = lambda {puts ‘Hello world’}  
Test.create\_method(:foo, proc)  
Test.foo #want this  
Integer.foo #don’t want this

The problem with the above is that create\_method adds foo to all  
classes. self.send on its own doesn’t seem to do what I want - it adds  
foo as instance method instead.

The method will eventually be placed in an module to be mixed in when  
desired, although I don’t think that matters here.

Ideas?

---

<div class="post-metadata">

**Author:** ![sshaikh](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/b77776/32.png) [@sshaikh](https://www.ruby-forum.com/u/sshaikh)\
**Post date:** [June 30, 2009, 11:44pm UTC](https://www.ruby-forum.com/t/dynamically-creating-class-methods/171351/2 "2009-06-30T23:44:12Z")

</div>

Hi –

On Wed, 1 Jul 2009, Shak Shak wrote:

> proc = lambda {puts ‘Hello world’}  
> Test.create\_method(:foo, proc)  
> Test.foo #want this  
> Integer.foo #don’t want this
> 
> The problem with the above is that create\_method adds foo to all  
> classes. self.send on its own doesn’t seem to do what I want - it adds  
> foo as instance method instead.

There are three candidates for the class to which you might send the  
:define\_method message:

1. Test
2. Class
3. the singleton class of Test

#3 is the one you want. The code you’ve written sends the message to  
Class, and the self.send that you’ve tried sends it to Test.

Try this:

class Test  
def self.create\_method(name, proc)  
s\_class = class \<\< self; self; end  
s\_class.send(:define\_method, name, proc)  
end  
end

There are other ways (including using class\_eval), but that’s the  
general idea.

David
