Ruby class_eval 方法 [英] Ruby class_eval method
本文介绍了Ruby class_eval 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在研究如何动态创建方法
I'm trying to figure out how to dynamically create methods
class MyClass
def initialize(dynamic_methods)
@arr = Array.new(dynamic_methods)
@arr.each { |m|
self.class.class_eval do
def m(*value)
puts value
end
end
}
end
end
tmp = MyClass.new ['method1', 'method2', 'method3']
不幸的是,这只创建了方法 m 但我需要根据 m 的值创建方法,想法?
Unfortunately this only creates the method m but I need to create methods based on the value of m, ideas?
推荐答案
接受的方式有两种:
@arr.each do |method|
self.class.class_eval do
define_method method do |*arguments|
puts arguments
end
end
end
使用带有字符串参数的class_eval:>
@arr.each do |method|
self.class.class_eval <<-EVAL
def #{method}(*arguments)
puts arguments
end
EVAL
end
第一个选项将闭包转换为方法,第二个选项计算字符串(heredoc)并使用常规方法绑定.在调用方法时,第二个选项具有非常小的性能优势.第一个选项(可以说)更具可读性.
The first option converts a closure to a method, the second option evaluates a string (heredoc) and uses regular method binding. The second option has a very slight performance advantage when invoking the methods. The first option is (arguably) a little more readable.
这篇关于Ruby class_eval 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文