Re: define_method in inheritance



Hi --

On Wed, 22 Jul 2009, Juston Davies wrote:

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!

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

--
David A. Black / Ruby Power and Light, LLC
Ruby/Rails consulting & training: http://www.rubypal.com
Now available: The Well-Grounded Rubyist (http://manning.com/black2)
Training! Intro to Ruby, with Black & Kastner, September 14-17
(More info: http://rubyurl.com/vmzN)

.



Relevant Pages

  • Re: File handle re-use woes using pipe within a loop
    ... > child will die before the parent has read the output from it. ... > definitions within the while loop. ... The whole point of 'my' variables is that when they go out of scope ...
    (comp.lang.perl.misc)
  • Re: define_method in inheritance
    ... On Wed, 22 Jul 2009, Juston Davies wrote: ... into a parent and then invoke it on a child would the new method be ... David A. Black / Ruby Power and Light, ...
    (comp.lang.ruby)
  • define_method in inheritance
    ... I had a quick question about something I had read in a book "The Ruby ... This opens up the scope of a given class so any other class could add ... into a parent and then invoke it on a child would the new method be ...
    (comp.lang.ruby)
  • Re: Timing Error
    ... Why can you not call a function or a sub in the child from the parent? ... the scope of the function Public and call it using the fully referenced ... record in the Page subform. ...
    (microsoft.public.access.formscoding)
  • Re: Use search scope from another portal site
    ... > I then go into child and tell it to associate itself with the search scope ... I go back to parent and do full updates on the indexes. ... And are you sure that you have a scope for it and it has an include ...
    (microsoft.public.sharepoint.portalserver)