Chapter 5

Functions and Blocks

So far in this tutorial, we’ve seen several examples of Ruby functions, blocks, and methods. In this chapter, we’ll learn how to define our own functions, we’ll deepen our understanding of blocks, and we’ll learn how to chain methods. As we’ll see, the three are closely related, and in fact all of them are variations on the same basic functional theme—one of the most important ideas in Ruby, and indeed in all of computing (Figure 5.1).

Images

Figure 5.1: Time to level up.

5.1 Function Definitions

As we saw in Section 1.2, function calls in Ruby consist of a name and zero or more arguments:

Get Learn Enough Ruby to Be Dangerous: Write Programs, Publish Gems, and Develop Sinatra Web Apps with Ruby 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.