Chapter 14. Callable and runnable objects

 

In this chapter

  • Proc objects as anonymous functions
  • The lambda (a.k.a. proc) method
  • Code blocks
  • The Symbol#to_proc method
  • Method objects
  • Bindings
  • The eval family of methods
  • Threads
  • Executing external programs

In addition to the basic, bread-and-butter method calls that account for most of what happens in your program, Ruby provides an extensive toolkit for making things happen in a variety of ways. You need two or more parts of your code to run in parallel? Create some Thread objects and run them as needed. Want to choose from among a set of possible functions to execute, and don’t have enough information in advance to write methods for them? Create an array of Proc objects—anonymous functions—and call the one you need. You can even isolate methods as objects and execute dynamically created strings as code.

This chapter is about objects that you can call, execute, or run: threads, anonymous functions, strings, even methods that have been turned into objects (rather than called by objects). We’ll look at all of these constructs along with some auxiliary tools—keywords, variable bindings, code blocks—that make Ruby’s inclusion of callable, runnable objects possible.

Be warned: runnable objects have been at the forefront of difficult and changeable topics in recent versions of Ruby. There’s no getting around the fact that there’s a lot of disagreement about how they should work, and rather of lot of complexity involved in how they do work.

14.1. Basic anonymous functions: the Proc class

14.2. Creating functions with lambda and ->

14.3. Methods as objects

14.4. The eval family of methods

14.5. Parallel execution with threads

14.6. Issuing system commands from inside Ruby programs

14.7. Summary