Attention to the Role Played by a Method

Is the method a command or a question?

Generally speaking, methods play one of two roles:

  • They answer a question.
  • They perform a command.

Examples of methods that are questions

If we have a user object, and users have a name, we’d ask the user object for its name by calling the name method. The user.name method returns the user’s name. Arrays know their size (the number of elements they have), so we can ask an array: [1, 2, 3].size returns 3.

Another example is the sort method on arrays. This method doesn’t actually sort the array that it’s called on. Instead, it returns a new array with the same values, but in sorted order. So, we’re essentially asking what the array would look like if it was sorted:

Press + to interact
array = [3, 2, 1]
p array.sort
p array

This outputs [1, 2, 3] and then [3, 2, 1]. So, we see that the original array is still the same.

Note: Oftentimes, questions need another bit of information passed. For example, we can ask a string if it begins with a certain character, and we’ll need to pass the character that we are talking about: "a string".start_with?("a"). The answer to this question is true. Or, if we ask an array if it includes a certain element, then, of course, we need to pass that element, as in [1, 2, 3].include?(1).

Methods executing certain commands

The other role that a method can play is being responsible for executing a certain command.

  • For example, in Rails, objects that can be stored in the database have a save method. The purpose of this method is to save the object to the database. For example, user.save saves some changes that we’ve made to the user before, like giving them a new password.

  • Another example is the sort! method on arrays. Different from the sort method without an exclamation mark, this method tells the array to sort itself:

Press + to interact
array = [3, 2, 1]
array.sort!
p array

This code prints out [1, 2, 3], and the array is now sorted.

  • Another example for a method that is a command is the puts method. All it does is print something to the screen, and it always returns nil.

Whenever we think about adding a new method to our code, it makes sense to consider the role the method should have. Is it a question or a command?

Note: In practice, we should always be aware of why we’re calling a certain method. For a print command, we probably aren’t interested in the return value, and we can simply discard it. When asking for the result after adding two, we want to use the return value later.