# Define\_method in inheritance

**URL:** <https://www.ruby-forum.com/t/define-method-in-inheritance/172462>\
**Category:** Ruby\
**Created:** [July 21, 2009, 11:12pm UTC](https://www.ruby-forum.com/t/define-method-in-inheritance/172462 "2009-07-21T23:12:28Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Juston\_Davies](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/e68b1a/32.png) [@Juston\_Davies](https://www.ruby-forum.com/u/Juston_Davies)\
**Post date:** [July 21, 2009, 11:12pm UTC](https://www.ruby-forum.com/t/define-method-in-inheritance/172462/1 "2009-07-21T23:12:28Z")

</div>

I had a quick question about something I had read in a book “The Ruby  
Way.” The author talks about different ways to dynamically define  
methods during runtime using something similar to the snippet below.

def define\_method (name, &array)  
self.class.send(:define\_method, name,&array)  
end

This opens up the scope of a given class so any other class could add  
methods on the fly. My question is that if I were to insert this code  
into a parent and then invoke it on a child would the new method be  
defined within the scope of the child or the parent? I’m concerned  
that this might result in adding methods into all the children rather  
than just the desired one. Let me know what you think. Thanks in  
advance!

---

<div class="post-metadata">

**Author:** ![Juston\_Davies](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/e68b1a/32.png) [@Juston\_Davies](https://www.ruby-forum.com/u/Juston_Davies)\
**Post date:** [July 21, 2009, 11:25pm UTC](https://www.ruby-forum.com/t/define-method-in-inheritance/172462/2 "2009-07-21T23:25:20Z")

</div>

Hi –

On Wed, 22 Jul 2009, Juston Davies wrote:

> into a parent and then invoke it on a child would the new method be  
> defined within the scope of the child or the parent? I’m concerned  
> that this might result in adding methods into all the children rather  
> than just the desired one. Let me know what you think. Thanks in  
> advance!

It will define the method in self.class, which will be the class of  
whatever object you call it on. The new method will also be available  
to instances of subclasses of that class.

class A  
def define\_method(name, &block)  
self.class.send(:define\_method, name, &block)  
end  
end

class B \< A  
end

class C \< B  
end

b = B.new  
b.define\_method(:x) { puts “In x!” }

b.x # In x!

c = C.new  
c.x # In x!

a = A.new  
a.x # Unknown method x

David

---

<div class="post-metadata">

**Author:** ![Juston\_Davies](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/e68b1a/32.png) [@Juston\_Davies](https://www.ruby-forum.com/u/Juston_Davies)\
**Post date:** [July 22, 2009, 12:03am UTC](https://www.ruby-forum.com/t/define-method-in-inheritance/172462/3 "2009-07-22T00:03:19Z")

</div>

Awesome, thats what I wanted to hear. Thanks for the help!
