To provide further clarification:
Joey says that the return behavior of Proc.new
is surprising. However when you consider that Proc.new behaves like a block this is not surprising as that is exactly how blocks behave. lambas on the other hand behave more like methods.
This actually explains why Procs are flexible when it comes to arity (number of arguments) whereas lambdas are not. Blocks don't require all their arguments to be provided but methods do (unless a default is provided). While providing lambda argument default is not an option in Ruby 1.8, it is now supported in Ruby 1.9 with the alternative lambda syntax (as noted by webmat):
concat = ->(a, b=2){ "#{a}#{b}" }
concat.call(4,5) # => "45"
concat.call(1) # => "12"
And Michiel de Mare (the OP) is incorrect about the Procs and lambda behaving the same with arity in Ruby 1.9. I have verified that they still maintain the behavior from 1.8 as specified above.
break
statements don't actually make much sense in either Procs or lambdas. In Procs, the break would return you from Proc.new which has already been completed. And it doesn't make any sense to break from a lambda since it's essentially a method, and you would never break from the top level of a method.
next
, redo
, and raise
behave the same in both Procs and lambdas. Whereas retry
is not allowed in either and will raise an exception.
And finally, the proc
method should never be used as it is inconsistent and has unexpected behavior. In Ruby 1.8 it actually returns a lambda! In Ruby 1.9 this has been fixed and it returns a Proc. If you want to create a Proc, stick with Proc.new
.
For more information, I highly recommend O'Reilly's The Ruby Programming Language which is my source for most of this information.