Explain the difference between a block and a Proc.
Last updated
A block is an anonymous chunk of code passed to a method; it is not an object on its own. A Proc is a block wrapped in an object that you can store in a variable, pass around, and call multiple times.
A block is syntax, not a value: Written with
do...endor{ }, a method may receive only one block, invoked withyieldor a&blockparameter.A Proc is a first-class object: Created with
Proc.new,proc { }, orlambda; stored, passed, and called with.call.Conversion between them: Prefixing a parameter with
&turns a passed block into aProcinside the method, and&on aProcturns it back into a block at the call site.Two flavors of Proc: Lambdas check argument count strictly and
returnonly from themselves; non-lambda procs are lenient andreturnfrom the enclosing method.