From: Rajinder Yadav Date: 2009-12-15T20:12:40+09:00 Subject: Re: meta-programming Jes�s Gabriel y Gal�n wrote: > On Tue, Dec 15, 2009 at 9:32 AM, Rajinder Yadav wrote: >> I am just starting to expand my Ruby knowledge into the area of >> meta-programming. >> >> I want to be able to create a class dynamically. Lets call it, class Person, >> and then I want to add methods to it dynamically. >> >> From a static point I have managed to compile the following example: >> >> class Person >> def self.extend_me >> class_eval "def greet; puts 'hello'; end" >> instance_eval "def name; puts 'Person'; end" >> end >> end >> >> Person.extend_me >> >> Person.respond_to? :greet >> Person.respond_to? :name >> >> puts Person.name >> p = Person.new >> puts p.greet >> >> >> How would I declared a, 'class Person' dynamically and then add methods and >> attributes to it? Can someone point me to good documentation on this or show >> me some simple code example? > > If you want to define the class dynamically, take a look at Class.new. > This creates an anonymous class that you can assign to a constant > directly or with const_set. > To define methods I would use define_method. Adding attributes is done > adding methods that set and get the attributes: > > irb(main):042:0> C = Class.new do > irb(main):043:1* def self.add_method(name, &blk) > irb(main):044:2> define_method(name, &blk) > irb(main):045:2> end > irb(main):046:1> end > => C > > irb(main):051:0> C.add_method(:name) {@name} > => # > irb(main):052:0> C.add_method(:name=) {|value| @name = value} > => # > irb(main):053:0> c = C.new > => # > irb(main):054:0> c.name=3 > => 3 > irb(main):055:0> c.name > => 3 > > Hope this helps, > > Jesus. > > Hi Jesus, yes it does help and you answered the next question I was about to ask about adding variables after reading Brian's reply. -- Kind Regards, Rajinder Yadav http://DevMentor.org Do Good! - Share Freely