如何根据传递的字符串数组定义模块内部的方法?
How to define the methods inside module based on passed array of strings?
我正在尝试用宏定义方法。当我尝试构建方法(见下文)时,我看到语法错误 for expression must be an array, hash or tuple literal, not Var:
.
module Test
def self.get_from_outside(methods)
build_methods(methods.to_a)
end
macro build_methods(methods)
{% for method in methods %}
def self.{{method.id}}_present?
true
end
{% end %}
end
end
t = Test
t.get_from_outside(["method_a", "method_b", "method_c"])
好的,节点有 Var 类型,宏不允许传递这种类型,但如果我直接传递数组,程序编译成功。现在我不能向外传递参数了。
module Test
METHODS = ["method_a", "method_b", "method_c"]
{% for method in METHODS %}
def self.{{method.id}}
true
end
{% end %}
end
t = Test
p t.responds_to?(:method_a)
#=> true
是否可以使用外部数组在模块内部定义方法?
使用宏时,可能最重要的正确概念是编译时执行与运行时执行。
宏在编译时执行,作为编译器的解释语言。当生成的二进制文件为 运行.
时,将执行所有其他代码
因此宏无法访问任何 运行时间数据,例如常规方法定义的参数。您可以通过生成将数据放在 运行time 期望的位置(例如特定变量)的代码,从宏转到 运行time。但显然你不能走另一条路。
因此,根据经验,您可以将数据从宏传递到方法,但反之则不行。
我正在尝试用宏定义方法。当我尝试构建方法(见下文)时,我看到语法错误 for expression must be an array, hash or tuple literal, not Var:
.
module Test
def self.get_from_outside(methods)
build_methods(methods.to_a)
end
macro build_methods(methods)
{% for method in methods %}
def self.{{method.id}}_present?
true
end
{% end %}
end
end
t = Test
t.get_from_outside(["method_a", "method_b", "method_c"])
好的,节点有 Var 类型,宏不允许传递这种类型,但如果我直接传递数组,程序编译成功。现在我不能向外传递参数了。
module Test
METHODS = ["method_a", "method_b", "method_c"]
{% for method in METHODS %}
def self.{{method.id}}
true
end
{% end %}
end
t = Test
p t.responds_to?(:method_a)
#=> true
是否可以使用外部数组在模块内部定义方法?
使用宏时,可能最重要的正确概念是编译时执行与运行时执行。
宏在编译时执行,作为编译器的解释语言。当生成的二进制文件为 运行.
时,将执行所有其他代码因此宏无法访问任何 运行时间数据,例如常规方法定义的参数。您可以通过生成将数据放在 运行time 期望的位置(例如特定变量)的代码,从宏转到 运行time。但显然你不能走另一条路。
因此,根据经验,您可以将数据从宏传递到方法,但反之则不行。