Creating Classes at Runtime

So far, you have modified classes and created new objects from existing classes. But how would you go about creating a completely new class at runtime? Well, just as you can use const_get to access an existing class, you can use const_set to create a new class. Here’s an example of how to prompt the user for the name of a new class before creating that class, adding a method (myname) to it, creating an instance (x) of that class, and calling its myname method:

create_class.rb

puts("What shall we call this class? ") className = gets.strip().capitalize() Object.const_set(className,Class.new) puts("I'll give it a method called 'myname'" ) className = Object.const_get(className) className::module_eval{ define_method(:myname){ ...

Get The Book of Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.