Methods can be defined and called dynamically using define_method and
send/method respectively. Shouldn't there be similar alternatives for
class creation and invocation? Maybe like this:
name = "A"
define_class(name) do
def say_hi
p "hi"
end
.
end
get_class(name).new.say_hi
I would like the above syntax better than the current way of doing it.
name = "A"
eval "class #{name}; end"
klass = Object.const_get(name)
klass.class_eval do
def say_hi
p "hi"
end
.
end
klass.new.say_hi
Methods can be defined and called dynamically using define_method and
send/method respectively. Shouldn't there be similar alternatives for
class creation and invocation? Maybe like this:
name = "A"
define_class(name) do
def say_hi
p "hi"
end
.
.
end
get_class(name).new.say_hi
I would like the above syntax better than the current way of doing it.
name = "A"
eval "class #{name}; end"
klass = Object.const_get(name)
klass.class_eval do
def say_hi
p "hi"
end
.
.
end
klass.new.say_hi
Methods can be defined and called dynamically using define_method and
send/method respectively. Shouldn't there be similar alternatives for
class creation and invocation? Maybe like this:
name = "A"
define_class(name) do
def say_hi
p "hi"
end
.
.
end
get_class(name).new.say_hi
I would like the above syntax better than the current way of doing it.
module Kernel
def define_class(name, &blk)
klass = self.class.const_set(name, Class.new(&blk))
end
def get_class(name)
self.class.const_get(name)
end
end
name = 'D'
klass = define_class(name) do
def say_hi
p "hi #{self.class.name}"
end
end