chapter fourteen

14 Callable and runnable objects

 

This chapter covers

  • Proc objects as anonymous functions
  • The lambda method for generating functions
  • Code blocks
  • Method objects
  • 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 concurrently? 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, or execute dynamically created strings as code.

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

14.1 Basic anonymous functions: the Proc class

14.1.1 Proc objects

14.1.2 Procs and blocks and how they differ

14.1.3 Block-proc conversions

14.1.4 Using Symbol#to_proc for conciseness

14.1.5 Procs as closures

14.1.6 Proc parameters and arguments

14.2 Creating functions with lambda and ->

14.3 Methods as objects

14.3.1 Capturing Method objects

14.3.2 The rationale for methods as objects

14.4 The eval family of methods

14.4.1 Executing arbitrary strings as code with eval

14.4.2 The dangers of eval

14.4.3 The instance_eval method

14.4.4 Using class_eval (a.k.a. module_eval)

14.5 Concurrent execution with threads

14.5.1 Killing, stopping, and starting threads

14.5.2 A threaded date server

14.5.3 Writing a chat server using sockets and threads

14.5.4 Threads and variables

14.5.5 Manipulating thread keys

14.6 Issuing system commands from inside Ruby programs

14.6.1 The system and exec methods and backticks

14.6.2 Communicating with programs via open and popen3

14.7 Summary