我正在编写一个动态创建类的函数。我遇到了* vars变量(下面)的问题,其中块内部传递给Class :: new,“def initialize”方法无法看到* vars的值(因此Ruby在* vars上报告未绑定的变量错误)。
怎么办?
谢谢!
class MyParentClass
def do_something_with(*args)
end
def do_something_else_with(*vars)
end
end
def create_class(class_name,*vars)
new_class = Class::new(MyParentClass) do
def initialize(*args)
super
do_something_with(args)
do_something_else_with(vars)
end
end
Object::const_set(class_name.intern,new_class)
end
# Ruby: Error: *vars is unbound variable
# My notes: *vars is in scope inside the do..end block passed to Class::new, but cannot be seen inside def initialize (why?) . And, how to fix this?
答案 0 :(得分:0)
我不确定你想用这个装置做什么,但是经过一些改变后它会起作用(好吧,取决于你对“工作”的定义):
class MyParentClass
def do_something_with(*args)
puts "something #{args.inspect}"
end
def do_something_else_with(*vars)
puts "else #{vars.inspect}"
end
end
def create_class(class_name,*vars)
new_class = Class::new(MyParentClass) do
define_method :initialize do |*args|
super()
do_something_with(*args)
do_something_else_with(*vars)
end
end
Object::const_set(class_name.intern,new_class)
end
create_class :MyClass, 1, :foo, :bar
MyClass.new(2, :baz)
使vars
可见的技巧是使用闭包来定义构造函数。