# Adding methods to an existing class

**URL:** <https://rubytalk.org/t/adding-methods-to-an-existing-class/7252>\
**Category:** ruby-talk\
**Created:** [6 August 2003 16:00 UTC](https://rubytalk.org/t/adding-methods-to-an-existing-class/7252 "2003-08-06T16:00:18Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Volkmann\_Mark](https://avatars.discourse-cdn.com/v4/letter/v/67e7ee/32.png) [@Volkmann\_Mark](https://rubytalk.org/u/Volkmann_Mark)\
**Post date:** [6 August 2003 16:00 UTC](https://rubytalk.org/t/adding-methods-to-an-existing-class/7252/1 "2003-08-06T16:00:18Z")

</div>

I’m fumbling over syntax trying to figure out how I could write a method  
that adds a method to a given class. I’d call it like this.

addTestMethod(Foo)

where Foo is a class.

addTestMethod would add a fixed “test” method to the class passed to it.

An example would be greatly appreciated!

> **···**
>
> * * *
> 
> A.G. Edwards & Sons’ outgoing and incoming e-mails are electronically  
> archived and subject to review and/or disclosure to someone other  
> than the recipient.
> 
> * * *

---

<div class="post-metadata">

**Author:** ![David\_A\_Black2](https://avatars.discourse-cdn.com/v4/letter/d/57b2e6/32.png) [@David\_A\_Black2](https://rubytalk.org/u/David_A_Black2)\
**Post date:** [6 August 2003 16:30 UTC](https://rubytalk.org/t/adding-methods-to-an-existing-class/7252/2 "2003-08-06T16:30:38Z")

</div>

Hi –

> I’m fumbling over syntax trying to figure out how I could write a method  
> that adds a method to a given class. I’d call it like this.
> 
> addTestMethod(Foo)
> 
> where Foo is a class.
> 
> addTestMethod would add a fixed “test” method to the class passed to it.
> 
> An example would be greatly appreciated!

def add\_test\_method(klass)  
klass.class\_eval {  
define\_method(:some\_test) { puts “testing!” }  
}

# or: klass.class\_eval “def some\_test; puts "testing!"; end”

# or (1.8.0 only):

# klass.class\_eval { def some\_test; puts “testing!”; end }

end

class A  
end

a = A.new  
add\_test\_method(A)  
a.some\_test # =\> testing!

(I’ve chosen “some\_test” so as not to interfere with Kernel#test.)

David

> **···**
>
> On Thu, 7 Aug 2003, Volkmann, Mark wrote:
> 
> –  
> David Alan Black  
> home: [dblack@superlink.net](mailto:dblack@superlink.net)  
> work: blackdav@shu.edu  
> Web: [http://pirate.shu.edu/~blackdav](http://pirate.shu.edu/~blackdav)
