如果一个块是一个闭包,为什么这段代码不起作用,该如何使其起作用?
def R(arg)
Class.new do
def foo
puts arg
end
end
end
class A < R("Hello!")
end
A.new.foo #throws undefined local variable or method `arg' for #<A:0x2840538>
块是闭包,arg
确实在Class.new
块内可用。只是因为def
开始一个新的作用域,所以它在foo
方法内不可用。如果您将def
替换为采用块的define_method
,则会看到所需的结果:
def R(arg)
Class.new do
define_method(:foo) do
puts arg
end
end
end
class A < R("Hello!")
end
A.new.foo # Prints: Hello!
define_method(:add_one) do |x| x+1 end
。 - sepp2kdef R(arg)
c = Class.new
# Send the block through as a closure, not as an inline method
# definition which interprets variables always as local to the block.
c.send(:define_method, :foo) do
arg
end
c
end
class A < R("Hello!")
end
puts A.new.foo.inspect
# => "Hello!"