Learn about the importance of methods.

Importance of methods

Programming is all about interacting with data. Consider Twitter, for example, which essentially takes 140 characters of text (which is data) from users and displays it to others.

We’ve already learned about the most important primitive (simple) types of data in Ruby: numbers, strings, true, false, and nil. We’ve also looked at the two most common data structures: arrays and hashes.

This all concerns data. Methods, on the other hand, are how we interact with that data.

In this section, we’ll look closer at the anatomy of a method, and we’ll learn how to implement and use our own methods.

Methods define behavior

Methods are all about defining behavior so that they can easily be applied to different bits of data in different contexts.

For example, there are methods that transform strings, sort arrays, read CSV or Excel files, send emails, sign in to Facebook, or send Tweets.

Another way of putting this is that methods are a way of assigning a name to a certain piece of code. Just like how a variable enables us to look up or refer to an object, methods enable us to execute pieces of code associated with that object.

Remember: Variables name things, methods name behavior (code).

Methods make code reusable by packaging (encapsulating) code and sticking a name on it.

As we’ve seen, Ruby comes with many methods predefined, or written by experienced programmers. So, unless we’re studying computer science and we’re faced with the exercise of implementing our own complicated sorting algorithms for data collections, we’ll simply use the sort method for arrays. This method is defined out of the box in Ruby.

Let’s explore what makes up a method, and how we can define our own.

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy