【发布时间】:2018-07-24 06:18:13
【问题描述】:
我正在尝试根据以下问题在 Ruby 中使用元编程创建类:Dynamically define named classes in Ruby。一切都很顺利,除了Class.new 的块中似乎无法引用方法参数,这很奇怪。
我有这个
class A; end
module B
def self.class_with_method(class_name, method_return)
klass = Class.new(A) do
def example
method_return
end
end
B.const_set class_name, klass
end
end
但是当我有上面的然后用它测试它
B.class_with_method 'ExampleClass', 23
B::ExampleClass.new.example
给我
#<:exampleclass:0x00007ff1d7130d00> (NameError) 的未定义局部变量或方法 `method_return'
这很奇怪,因为如果我要这样做
def add_number(number)
[1, 2, 3, 4].map {|i| i + number}
end
add_number(2)
# => [3, 4, 5, 6]
很明显,块可以接受方法参数。
有没有办法在块内将method_return 传递给def example?
【问题讨论】:
标签: ruby