How do I dynamically define a class in Ruby WITH a name?
I know how to create a class dynamically without a name using something like:
dynamic_class = Class.new do
def method1
end
end
But you can't specify a class name. I want to create a class dynamically with a name.
Here's an example of what I want to do but of course it doesn't actually work.
(Note that I am not creating an instance of a class but a class definition)
class TestEval
def method1
puts "name: #{self.name}"
end
end
class_name = "TestEval"
dummy = eval("#{class_name}")
puts "dummy: #{dummy}"
dynamic_name = "TestEval2"
class_string = """
class #{dynamic_name}
def method1
end
end
"""
dummy2 = eval(class_string)
puts "dummy2: #{dummy2}" # doesn't work
Actual output:
dummy: TestEval
dummy2:
Desired output:
dummy: TestEval
dummy2: TestEval2
======================================================
Answer: A totally dynamic solution using sepp2k's method
dynamic_name = "TestEval2"
Object.const_set(dynamic_name, Class.new) # If inheriting, use Class.new( superclass )
dummy2 = eval("#{dynamic_name}")
puts "dummy2: #{dummy2}"
class A ... enddoes not evaluate tonil, it evaluates to the value of the last expression evaluated inside it, just like every other compound expression (blocks, methods, module definitions, expression groups) in Ruby. It just so happens that in many class definition bodies, the last expression is a method definition expression, which evaluates tonil. But it is sometimes useful to have a class definition body evaluate to a specific value, e.g. in theclass << self; self endidiom.