This one was a bit tricky to track down. Looking at the docs for Proc#lambda?
for 1.9, there's a fairly lengthy discussion about the difference between proc
s and lamdba
s.
What it comes down to is that a lambda
enforces the correct number of arguments, and a proc
doesn't. And from that documentation, about the only way to convert a proc into a lambda is shown in this example:
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
If you want to avoid polluting any class, you can just define a singleton method on an anonymous object in order to coerce a proc
to a 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
Mark Rushakoff
2010-06-01 00:54:52