Ruby’s ampersand prefix operator converts between a method call’s block and a callable object. In a method definition, &block captures the supplied block as a Proc; in a call, &proc supplies a Proc—or another object’s to_proc result—as the block. section 14.1.3 section 14.7
Capture a block as a Proc
def capture_block(&block) puts "Got block as proc" block.call end capture_block { puts "Inside the block" } The & parameter performs an implicit Proc conversion, so block becomes an object that can be called inside the method. section 14.1.3
The same marker works on the calling side. Passing capture_block(&p) makes p serve as the method’s block. Because one call can have only one block, capture_block(&p) { ... } raises an error: Ruby cannot choose between the converted Proc and the inline block. section 14.1.3
Common forms include:
- &block in a parameter list captures a block as a Proc. section 14.1.3
- &p in a method call converts p through to_proc and uses the result as the block. section 14.1.3
- &:method is shorthand for applying Symbol#to_proc, as in ["havoc", "prodigy"].map(&:capitalize). section 3.6.3
Use an object as a block
albums = { 1988 => "Straight Outta Compton", 1993 => "Midnight Marauders", 1996 => "The Score", 2004 => "Madvillainy", 2015 => "To Pimp a Butterfly", 2025 => "Alfredo 2" } [1988, 1996].map(&albums) # => ["Straight Outta Compton", "The Score"] The hash responds through to_proc, allowing map to call it for each element. section 14.7
def Ticket.most_expensive(*tickets)
tickets.max_by(&:price)
end
Inspect &:price inside max_by: the symbol becomes a Proc that sends price to each ticket, supplying the comparison block. section 3.6.3
