Callable Objects

Where you learn how blocks are just part of a larger family, and Bill shows you how to set code aside and execute it later.

If you get to the bottom of it, using a block is a two-step process. First, you set some code aside, and second, you call the block (with yield) to execute the code. This “package code first, call it later” mechanism is not exclusive to blocks. There are at least three other places in Ruby where you can package code:

  • In a proc, which is basically a block turned object
  • In a lambda, which is a slight variation on a proc
  • In a method

Procs and lambdas are the big ones to talk about here. We’ll start with them and bring methods back into the picture later.

Proc Objects

Although most things in Ruby are objects, ...

Get Metaprogramming Ruby 2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.