liveBook · Manning

Block-to-proc conversion

As explained in The Well-Grounded Rubyist, Fourth Edition

A block-to-proc conversion is the conversion of a Ruby code block into a Proc object.

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.

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains implicit Proc creation, & syntax, invocation, reverse conversion, and the explicit-block conflict.
Examples
Uses capture_block, explicit Proc arguments, hash lookup, map, and compact examples.
What you can do after
Apply block-to-Proc conversion to capture, invoke, and pass executable behavior between methods.
How it connects
Connects blocks, methods, Proc objects, method arguments, and callable hashes.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.