Ruby can capture a method’s code block as a Proc object by marking the parameter with &, allowing the method to call the block explicitly. section 14.1.3
def capture_block(&block)
puts "Got block as proc"
block.call
end
capture_block { puts "Inside the block" }
The &block parameter performs the conversion; block.call then executes the resulting Proc. section 14.1.3
Conceptually, calling capture_block with a block creates a Proc from that block and binds the new object to block. The special & syntax distinguishes this conversion from ordinary argument binding. section 14.1.3
The conversion works in both directions:
- Use & on a method parameter to receive a supplied block as a Proc. section 14.1.3
- Use & on a Proc argument to make that Proc serve as the method’s block. section 14.1.3
- Do not supply both an &-converted Proc and an explicit block in the same call. section 14.1.3
Applying a Proc as a block
A hash can become callable and then act as a mapping block: albums.to_proc followed by [1988, 1996].map(&albums) returns the corresponding album names.
