Methods

Learn about methods and how to use them in Ruby.

Purpose of methods

Methods, or functions, are small chunks of code that we can reuse. Until now, we haven’t reused the code that we wrote, except for the code inside of blocks. But with methods, we can improve and optimize our programs by splitting them into multiple logical blocks.

Methods shouldn’t necessarily make our programs shorter. The main idea is to define the logical parts and make the program more readable for a human. Sometimes, this process is called refactoring. There are many refactoring techniques, and this particular technique is called the extract method. The result of this refactoring is logical blocks of code that are extracted into one or more methods, so that the code can be reused later.

We can also introduce methods for our own convenience. Remember how we used the following code to convert user input to a number?

age = gets.to_i

The code given above gets the user input and converts it from a string to an integer with .to_i and saves the result to the age variable. This expression isn’t self-explanatory for someone who sees the code for the first time. Let’s improve it a little, so that it becomes easier to understand:

Get hands-on with 1200+ tech skills courses.