是否可以将 proc 风格的 Proc 转换为 lambda 风格的 Proc?
有点惊讶这行不通,至少在 1.9.2 中是这样:
my_proc = proc {|x| x}
my_lambda = lambda &p
my_lambda.lambda? # => false!
最佳答案
追踪这个有点棘手。查看 Proc#lambda?
for 1.9 的文档,关于 proc
和 lamdba
之间的区别有相当长的讨论。
归根结底,lambda
会强制执行正确数量的参数,而 proc
则不会。从该文档中,此示例显示了将 proc 转换为 lambda 的唯一方法:
define_method
always defines a method without the tricks, even if a non-lambda Proc object is given. This is the only exception which the tricks are not preserved.class C define_method(:e, &proc {}) end C.new.e(1,2) => ArgumentError C.new.method(:e).to_proc.lambda? => true
如果你想避免污染任何类,你可以只在匿名对象上定义一个单例方法,以便将 proc
强制转换为 lambda
:
def convert_to_lambda &block
obj = Object.new
obj.define_singleton_method(:_, &block)
return obj.method(:_).to_proc
end
p = Proc.new {}
puts p.lambda? # false
puts(convert_to_lambda(&p).lambda?) # true
puts(convert_to_lambda(&(lambda {})).lambda?) # true
关于Ruby:将 proc 转换为 lambda?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2946603/