liveBook · Manning

Callable

As explained in The Well-Grounded Rubyist, Fourth Edition

A callable object is an object that provides a way to invoke encapsulated behavior as a function-like operation.

A callable object is an object that responds to call by executing associated behavior. Ruby’s main callable objects are Proc objects, lambdas, and method objects. section 14.1

Callable objects let code behave like data:

  • Create a Proc from a code block, store it in a variable or array, pass it as an argument, and execute it later. section 14.1.1
  • Use lambdas as a specialized kind of Proc object, or extract methods into method objects for storage and execution. section 14.1
  • Invoke callable objects with call, square brackets, or the dot-parentheses form; brackets are synonymous with call. section 14.3.2

A callable closure

A method can return a Proc that remembers a value from its creation context: `multiply_by(10)` returns a Proc whose later calls multiply their argument by 10. The preserved context also allows a counter Proc to retain and update its private state across calls. section 14.1.5

pr = Proc.new { puts "Inside a Proc's block" }

Inspect a minimal Proc definition before calling it with `call`; the block becomes the Proc’s executable body. section 14.1.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains Proc creation, invocation syntax, closures, variable bindings, and method objects, while deferring exhaustive callable behavior.
Examples
Demonstrates Proc blocks, multiplier closures, preserved local context, counters, method binding, and alternate invocation syntax.
What it assumes
Assumes Ruby methods, local variables, code blocks, and object messaging, while building callable behavior from Proc.new.
What you can do after
Apply it via Ruby Procs, lambdas, and method objects to defer, pass, select, and invoke behavior.
How it connects
Connects callable objects with Proc objects, lambdas, method objects, code blocks, closures, and functional programming.

Also explained in

Compare how 5 books explain callable →

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.