我正在努力实现预期的输出,但未能为以下问题陈述创建可重用代码。有什么建议么?

I am trying hard to achieve expected output, but failing to create a reusable code for below problem statement. Any suggestions?

动态定义一个class。 Class 名称应通过标准输入(命令行)从用户那里获取 然后提示用户输入方法名称和一行代码。该方法应定义为上面class中的实例方法,由用户输入动态代码。 告诉用户 class 和方法已定义。 然后调用这个实例方法并显示结果

我想做的是 - "Making a class with initialize method which takes the dynamic class name method and then creating class there, after that creating an instance of that class there only in initialize method.Then assigning it to a class instance variable and calling the greet method/ dynamic method on that instance." 但是在这个过程中失败了。 我想用 OOPS 做到这一点,主要问题是接受用户输入并将其分配给动态方法和 class.

class MethodCreator
  @my_class_instance_var = ""

  class << self
    attr_accessor :my_class_instance_var
   end

  def initialize(class_name)
    cl = Class.new
    @my_class_instance_var = Object.const_set(class_name, cl)
  end
  def create_method(method_name, code_str)
    self.class.define_method(method_name, code_str)
  end
end

puts "Please enter the class name:"
class_name = gets.chomp
puts "Please enter the method name you wish to define:"
method_name = gets.chomp
puts "Please enter the method's code:"
code_str = gets.chomp

obj = MethodCreator.new(class_name)

obj.my_class_instance_var.method_name

预计:

Please enter the class name: User
Please enter the method name you wish to define: greet
Please enter the method's code: "Welcome from #{self.class} class. I am #{self}"

--- Result ---
Hello, Your class User with method greet is ready. Calling: User.new.greet:
"Welcome from User class. I am <User#123456>"

找到解决此问题的方法。如果这可以帮助像我一样正在为元编程苦苦挣扎的人,我将很高兴。

class MethodCreator
  def initialize(class_name)
    @klass = Class.new
    Object.const_set(class_name, @klass)
  end
  def new_method(method_name, code_str)
    @klass.instance_eval do
        define_method(method_name) { instance_eval(code_str)}
    end
  end
  def call(method_name)
    @klass.new.send(method_name)
  end
end

puts "Please enter the class name:"
class_name = gets.chomp
puts "Please enter the method name you wish to define:"
method_name = gets.chomp
puts "Please enter the method's code:"
code_str = gets.chomp

obj = MethodCreator.new(class_name)

obj.new_method(method_name, code_str)
puts obj.call(method_name)