在 Ruby 中,您将如何定义方法
def make_class(method_name, method_body, s_value)
通过以下实现返回一个类
class Anonymous
def method_name(args)
method_body(args)
end
def to_s
return s_value
end
end
如果您可以链接到您认为对基本 Ruby 元编程有用的任何资源,那也很棒。
最佳答案
你可以这样使用:
def make_class(s_value, method_name, &method_body)
Class.new do
define_method method_name, method_body
define_method :to_s do
s_value
end
end
end
klass = make_class 'foo instance', :foo do |*args|
"called foo with #{args.inspect}"
end
k = klass.new
puts k.to_s # => foo instance
puts k.foo [1, 2], 'hello' # => called foo with [[1, 2], "hello"]
在这种情况下,您应该将方法的主体作为 block 传递(您可以将 |*args|
替换为您希望作为方法参数的任何参数列表)。如果你不想将 method_body
作为 block 而是作为字符串传递,那么 eval
是你的 friend 。
关于ruby-on-rails - 如何在 Ruby 中动态创建具有给定方法和方法体的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8261079/