我希望实现类似下面的内容。根据数组参数定义方法名称并调用它们。
arr = ['alpha', 'beta', 'gamma'] arr.each { |role| # If the method already exists don't define new if ! method_exist? "init_#{role}" define "init_#{role}" p "I am method init_#{role}" end } init_beta init_gamma
编辑: 如果这种方法已经存在,请不要定义新方法。
答案 0 :(得分:1)
执行以下操作:
arr = ['alpha', 'beta', 'gamma']
arr.each do |role|
# this code is defining all the methods at the top level. Thus call to
# `method_defined?` will check if any method named as the string argument
# is already defined in the top level already. If not, then define the method.
unless self.class.private_method_defined?( "init_#{role}" )
# this will define methods, if not exist as an instance methods on
# the top level.
self.class.send(:define_method, "init_#{role}" ) do
p "I am method init_#{role}"
end
end
end
init_beta # => "I am method init_beta"
init_gamma # => "I am method init_gamma"
查看private_method_defined
和define_method
的文档。
注意:我在顶层使用了private_method_defined?
,您将定义的所有实例方法(在默认辅助功能级别使用def
或define_method
),成为Object
的私有实例方法。现在根据您的需要,您还可以相应地检查protected_method_defined?
和public_method_defined?
。