Rajinder Yadav wrote:
> How would I declared a, 'class Person' dynamically
Option 1: since you're using string eval already, you could just do the
same.
eval "class Person; end"
Option 2:
Person = Class.new # superclass is Object
Person = Class.new(Mammal) # superclass is Mammal
I find this isn't often done in practice though. A program which doesn't
know in advance which classes it has can be a bit too dynamic

You
would probably register your classes somewhere to be able to find them.
In a Hash is one option; under a Module is another, so you can use
MyModule.constants
to find them all.
You can make your classes anonymous if you don't bind them to a
constant:
my_klass = Class.new
> and then add methods and attributes to it?
As you've done before, using string eval, is one way.
Another way:
Person.class_eval { define_method(:greet) { puts "Hello" } }
This means that the method is a closure, and can access variables
outside (unlike 'def' which starts a fresh scope), and this can be
useful sometimes.
Another way: put the method(s) of interest in module(s), then include
the relevant ones.
Person.class_eval { include Greeter }
ActiveRecord is a plentiful source of examples.
--
Posted via
http://www.ruby-forum.com/.