liveBook · Manning

To_proc

As explained in The Well-Grounded Rubyist, Fourth Edition

Symbol#to_proc creates a Proc that sends the symbol as a method name to each object it receives.

A method call for every element

`%w{ david black }.map(&:capitalize)` returns `["David", "Black"]`. It does the same job as `map { |str| str.capitalize }`: each string receives `capitalize`. section 14.1.4

The shorthand has two parts. `:capitalize` is a Symbol naming the method; `&` calls its `to_proc` method and supplies the resulting Proc as the call’s block. The Proc sends that method name to each object it receives. Removing the parentheses—`map &:capitalize`—does not turn it into a literal block. section 14.1.4

class Symbol
  def to_proc
    Proc.new {|obj| obj.public_send(self) }
  end
end

A simplified implementation makes the dispatch visible: the returned Proc accepts an object and uses `public_send(self)` to send it the method named by the symbol. section 14.1.4

`&` works with other objects that provide `to_proc`. A Proc’s `to_proc` returns itself; a Hash can supply a Proc for lookups, as in `[1988, 1996].map(&albums)`. Keep the `&`: passing a Proc as an ordinary argument does not make it the block. Nor can one call supply both an `&`-marked argument and an inline block. section 14.1.3 section 14.7

Choose a maximum by calling a method

`tickets.max_by(&:price)` uses each ticket’s `price` as the comparison value. The shorthand fits when the block’s job is simply to call a named method on each item. section 3.6.3

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains ampersand conversion, block-argument constraints, and a simplified Symbol#to_proc implementation.
Examples
Uses string capitalization with map, ticket prices with max_by, and album lookups with a hash.
What it assumes
Assumes familiarity with Ruby methods, symbols, and map while explaining how ampersand converts an argument into a block.
What you can do after
Build it from scratch as a simplified Symbol#to_proc, then apply its shorthand to method-calling blocks.
How it connects
Connects symbols, Proc objects, blocks, public_send, Hash#to_proc, and enumerable methods.

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.