Can I create Ruby classes within functions bodies ? I seem to be getting error which tells me its not allowed but I think it should be as classes are too objects here.
You can create classes from within methods and assign them to a constant, as in the following
class A
def create_class class_name
new_class = Class.new
new_class.send :define_method, :speak do
"Hi, There"
end
Object.const_set class_name, new_class
end
end
A.new.create_class "Harry"
h = Harry.new
puts h.speak # responds => "Hi, There"
because a class name as in String is just a constant in ruby unlike many other languages.