From: Keith Rarick Date: 2007-08-04T07:24:28+09:00 Subject: Re: method_added hook and class methods Nobuyoshi Nakada wrote: > Hi, > > At Fri, 3 Aug 2007 15:29:06 +0900, > Keith Rarick wrote in [ruby-talk:263159]: >> Now I want to observe when class methods are defined. My understanding >> of ruby says that "class methods" are really just instance methods of >> the metaclass. So I do this: >> >> class C >> class << self > def singleton_method_added(name) > puts 'added ' + name.to_s > end Thanks very much! This works perfectly. Out of curiosity, why are metaclasses treated differently than regular classes in this respect? Suppose I am given a variable, x, that contains a class. The object may be either a class or a metaclass, and I wish to observe the creation of instance methods on x. Now I must do one of two different things depending on the type of x (class or metaclass). (For the sake of brevity, I assume a metaclass() method and ignore the fact that define_method() is private.) If x is a regular class: x.metaclass.define_method(:method_added) { |name| puts "added #{name}" } or, if x is a metaclass: x.define_method(:singleton_method_added) { |name| puts "added #{name}" } Further, I do not know of a reliable way to determine if x is a regular class or a metaclass, so I must actually do *both* if I want to be sure to see the addition of a method on x. Is this an accurate description or am I missing something? kr -- Posted via http://www.ruby-forum.com/.