定义用于Ruby中元编程的方法参数 [英] Define method parameters for meta programming in Ruby
问题描述
在Ruby中,我们可以使用元编程来定义实例方法,例如:
In Ruby, we can define instance methods with meta-programming like:
define_method(:hi) { 'Hello, SO world!' } # => :hi
hi # => "Hello, SO world!"
通过这种方式,可以使用动态名称定义一个方法:
This way, it is possible to define a method with a dynamic name:
dynamic_name = :hi # => :hi
define_method(dynamic_name) { 'Hello, SO world!' } # => :hi
hi # => "Hello, SO world!"
我们还可以将参数注入动态方法:
We can also inject arguments in to a dynamic method:
dynamic_name = :hi # => :hi
define_method(dynamic_name) do |arg1, arg2, &block|
'Hello, SO world!'
end # => :hi
hi(42, 42) { 42 } # => "Hello, SO world!"
到目前为止,很好.
但是我们该怎么做才能注入动态参数?
可以用动态符号替换arg1, arg2, &block
吗?
But how could we do to inject dynamic arguments?
Would it be possible to replace arg1, arg2, &block
by a dynamic notation?
感谢任何提示,最佳做法,甚至想法.
Thanks for any tips, best practices, or even ideas.
修改:
换句话说,我也想动态地定义实例方法的参数和块.
In other words, I would like to dynamically also define the parameters and the block of an instance method.
但是,我想使用特定数量的参数(可能为0),一个数组作为选项,并完成该方法的块.
However, I would like to do so with a particular number of parameters (which could be 0), an array in option, and to finish the block of the method.
这样,我可以避免使用诸如以下的方法:
This way, I could avoid having methods such as:
dynamic_name = :hi # => :hi
define_method(dynamic_name) do |*args, &block|
'f'
end # => :hi
hi # => "f"
hi(:foo) # => "f"
hi(:foo, :fooo) # => "f"
hi(:foo, :fooo, :foooo) # => "f"
...这是胡说八道,因为在这里我们可以为该方法提供无限数量的未使用参数.我想避免这种情况.
...which is a nonsense, because here we can give to the method an infinite number of unused parameters. I would like to avoid this situation.
编辑2 :
原因如下:
在Ruby中,当我们需要不需要任何参数的方法时,我们可以简单地做到:
In Ruby, when we need a method which do not need any parameters, we can simply do:
def my_method
"Hello, SO world!"
end
但是,如果相反,我会这样做:
However, if instead I do this:
def my_method(*args)
"Hello, SO world!"
end
...结果仍然相同,但是由于参数(数组args
)没有用,因此最好通过将其从方法中删除来保持简单.
...the result is still the same, but because the parameter (the array args
) is useless, it would be better to keep it simple by removing it from the method.
推荐答案
尝试传递数组或字典.
更新:
if condition1
class_eval <<-EVAL
def #{"my_method"}(arg1)
end
EVAL
else
class_eval <<-EVAL
def #{"my_method"}
end
EVAL
end
UPDATE2:
if condition1
self.instance_eval <<-EVAL
def #{"my_method"}(arg1)
end
EVAL
else
self.instance_eval <<-EVAL
def #{"my_method"}
end
EVAL
end
UPDATE3:
# or
self.instance_eval("def method1(arg1) puts 'hellowa' + arg1.to_s; end")
self.instance_eval("def method2() puts 'hellowa2'; end")
# and then
method1(33) # => hellowa33
method2 # => hellowa2
这篇关于定义用于Ruby中元编程的方法参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!