Sean O'Halpin
2/7/2006 12:34:00 AM
On 2/6/06, Paatsch, Bernd <BPaatsch@activevoice.com> wrote:
> Hello,
>
> I am fairly new to ruby and need some help
> I am structuring my code using classes.
> The application I work on requires input data. This data may require all or
> some of the classes I create. Instead of having a section in the main code
> creating all classes I would like to create only those classes that I need
> while reading the data. However I do not know how to do that.
Class names are constants. To get a reference to a class from a name
(String or Symbol):
klass = Object.const_get(classname)
Here's an example to get you going:
class Class1
def run
puts "You chose class 1"
end
end
class Class2
def run
puts "You chose class 2"
end
end
# this roundabout way of defining the class name is to emphasise
# that you can construct the class name dynamically
n = "1"
classname = "Class#{n}"
klass = Object.const_get(classname)
obj = klass.new
obj.run
#=> You chose class 1"
Regards,
Sean