下面的动态方法调用代码怎么写?

How to write the dynamic method calling code below?

Define a class dynamically. Class name should be taken from user by standard input (command line)

Then prompt user for a method name and a single line of code. This method should be defined as instance method in the class above dynamically with the code entered by user.

Tell user that the class and method is defined. Then call this instance method and display the result.

我可以动态创建 class 但之后我无法继续。

class Ancestor; end
SomeClass = Class.new(Ancestor) do
  def initialize(var)
     print "#{self.class} initialized with #{var}"
  end
end

class << self
 define_method :new_dynamic_method do
    "content goes here"
 end
end

puts a = SomeClass.new(ARGV[0])

代码应该是面向对象的。

预期结果:

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}"

--- 结果 ---

Hello, Your class User with method greet is ready. Calling: User.new.greet: "Welcome from User class. I am "

调用 API 应该类似于:

my_class = DynamicClass.new(class_name)
my_class.def_method(method_name, method_body)
my_class.def_method(another_method_name, method_body)
...
...

my_class.call(method_name)
my_class.call(another_method_name)

我们只看核心问题,不是获取用户的输入,也不是展示给用户阅读的信息。我们从用户那里获得以下信息:

class_name  = "User"
method_name = "greet"
code_str    = "Welcome from #{self.class} class. I am #{self}"
  #=> "Welcome from Object class. I am main"

创建 class:

cl = Class.new
  #=> #<Class:0x0000563cd2e3d748> 

命名 class:

Object.const_set(class_name, cl)
  #=> User

为 class 创建一个实例方法:

cl.define_method(method_name) { code_str }
  #=> :greet 

确认 class 已创建并列出 class 拥有的实例方法:

User.is_a? Class
  #=> true

User.instance_methods(false)
  #=> [:greet]

执行class'实例方法1:

User.new.greet
  #=> "Welcome from Object class. I am main"

参见 Class::new and Module#const_set, Module#define_method and Module#instance_methods

1.问题的 setter 可能希望 User.new.greet 到 return "Welcome from User class. I am #<User:0x00005cb777dca6f0> ",但这是不可能的,因为 #{self} 在 [=19] 时被评估为其当前值=]被赋值,如上图