Procs and Blocks

I think the difference between Procs and blocks, especially in the context of passing them as method arguments could have been explained a little clearer and earlier on in the section. The following line in particular was a little misleading:

The & way only allows you to pass a single block/proc to a method.

I understand that a block is a proc, but the sentence makes it seem like they can be passed interchangeably as an argument when the & is used, when really the & can only take blocks that are already stored in a Proc object, not the raw block itself. This was elaborated on a bit later on but was still confusing to me, especially since it was in the context of a new concept (Symbols and Blocks). The following example helped me understand this concept of “procification”, and I thought it may be helpful to include something similar in the section.

> def takes_proc(prc)
>   prc.call
> end
>
> def takes_block(&prc) 
>   prc.call
> end
>
> # The parameters are named "prc" in both methods since they are Procs in both cases. But in
> # the second case, the block is procified by the & and stored in the prc variable.
>
> prc = Proc.new { "A Proc object was passed in" }
>
> takes_proc prc 
=> "A Proc object was passed in"
>
> takes_block prc 
ArgumentError: wrong number of arguments (given 1, expected 0)
>
> takes_proc { "A block was passed in" }
ArgumentError: wrong number of arguments (given 0, expected 1)
>
> takes_block { "A block was passed in" }
=> "A block was passed in"
4 Likes