Improve the Behavior by Using a Routine

Learn how to code routines.

Introducing a routine

Up to this point, we’ve been showing the number of letters by explicitly setting the display (by using puts "_ _ _ _ _"). Since we’ve set the hidden_word, the current game only offers one hidden word.

We will, of course, consider having other words. Therefore we must be able to show the number of letters depending on the word we hide. And we do this dynamically.

Let’s introduce a new concept offered by Ruby language called “function,” “method,” or “routine”. The name routine is the one that is best suited.

When we do something that we repeat over and over, we say that we accomplish a routine task. The task is broken down into a sequence of actions or operations that we perform in the same order. The programming languages allow defining a series of operations or instructions, grouping them, and giving a name to the group. Such a group of operations, togather with its name, is what we call a routine (or function).

In Ruby, we define such a group using the def word (from “define”), followed by the name we want to give the group. We then provide the sequence of instructions. Finally, we end the group with the end word.

The name is significant because we will later use it to refer to the group of instructions performing a routine task. The name is simply the name of the message that we send. When Ruby manages the sending of the message, it searches what action is to be executed from among the names of the routines that have been defined.

As we already mentioned, in Ruby, the processing of a message always produces a result. The result is what the last instruction of the sequence produces.

Let’s add a routine that builds the information to show the number of letters.

Get hands-on with 1400+ tech skills courses.