Ruby 通过参数或字符串调用类方法的替代方法
我想传递一个类方法作为参数,让另一个对象调用它Ruby 通过参数或字符串调用类方法的替代方法,ruby,Ruby,我想传递一个类方法作为参数,让另一个对象调用它 do_this(Class.method_name) 然后: def do_this(class_method) y = class_method(local_var_x) end def do_this(method, x) y = method.call(x) end 我能看到的唯一方法是将其作为字符串传递并使用eval,或者将类和方法作为字符串传递,然后进行常量化并发送。eval的缺点似乎是速度和调试 有没有更简单的方法 编辑
do_this(Class.method_name)
然后:
def do_this(class_method)
y = class_method(local_var_x)
end
def do_this(method, x)
y = method.call(x)
end
我能看到的唯一方法是将其作为字符串传递并使用eval,或者将类和方法作为字符串传递,然后进行常量化并发送。eval的缺点似乎是速度和调试
有没有更简单的方法
编辑:
回答很好,但意识到我问的问题有点错,我想使用一个未随方法传递的参数。我建议使用一种类似于您提出的第二种解决方案的方法
do_this(Class.method(:name), x)
然后:
def do_this(class_method)
y = class_method(local_var_x)
end
def do_this(method, x)
y = method.call(x)
end
另请参阅。的文档。我建议采用类似于您提出的第二种解决方案的方法
do_this(Class.method(:name), x)
然后:
def do_this(class_method)
y = class_method(local_var_x)
end
def do_this(method, x)
y = method.call(x)
end
另请参阅的文档。考虑使用proc对象:
def do_this(myproc)
y = myproc.call
end
然后
do_this( Proc.new { klass.method(x) } )
你也应该考虑使用Bug,这比Ruby风格多。这看起来像:
def do_this
y = yield
end
及致电:
do_this { klass.method(x) }
考虑使用proc对象:
def do_this(myproc)
y = myproc.call
end
然后
do_this( Proc.new { klass.method(x) } )
你也应该考虑使用Bug,这比Ruby风格多。这看起来像:
def do_this
y = yield
end
及致电:
do_this { klass.method(x) }