The variable name not available in the class definition area ( class << self ). This does not throw a NameError because you have overridden method_missing .
To do what you are trying to do, you need to save the area with name . To do this, you need to use only block-based methods (e.g. class_eval ) instead of directly opening the class, so something like this:
def method_missing(meth,*args,&block) name = meth.to_s eigenclass = class << self; self; end eigenclass.class_eval do define_method(name) do puts "hello " + name end end end
But in fact, the symbol in meth is quite sufficient - you don’t need a name at all. (Although you will still need the above method anyway.) Also, you want to execute this method immediately. The easiest way is to simply send a message:
def method_missing(meth,*args,&block) eigenclass = class << self; self; end eigenclass.class_eval do define_method(meth) do puts "hello #{meth}" end end send(meth, *args, &block) end
source share