From: Josh Cheek Date: 2010-05-18T09:01:20+09:00 Subject: Re: Dynamically adding methods to a class --0016e6d998fa6d613e0486d30a1a Content-Type: text/plain; charset=ISO-8859-1 On Mon, May 17, 2010 at 6:25 PM, Sam Uel wrote: > Hi! > > I'm trying to add a method dynamically to a class by opening an existing > class, and it actually works. What I don't understand is why it doesn't > show up when I use the "methods" method on it afterwards. > > What I do is something like this: > Code: > > def method_missing name, *args > > Array.class_eval "def #{name} *args; #{str}; end" > > end > > Afterwards I can call that method on every object of this class (new or > otherwise). However, it doesn't show up in Array.methods. > > The Array.methods.length is the same both before and after that line is > executed and adds the method. However, if I do a self.methods.length the > number of methods has increased. > > My question is therefore this: how can I add a method to a class (e.g. > Array) and have it show up when I do a .methods on it? > > > Thanks in advance for any help! > -- > Posted via http://www.ruby-forum.com/. > > It is not being defined for the Array class, but rather for instances of the Array class. Try: Array.instance_methods --0016e6d998fa6d613e0486d30a1a--