Calling Methods

Learn how to call an object's methods in Ruby.

We'll cover the following

Calling methods

In Ruby, methods that are defined on objects can be used by adding a dot and then the method name, like so:

object.method

That essentially instructs an object to perform the method’s behavior.

This is known as calling a method.

For example, the String class defines methods like:

  • upcase (convert the object to uppercase)
  • downcase (convert the object to lowercase)
  • length (returns the string’s length)

Here’s how we can call them:

Press + to interact
name = "Ruby Monstas"
puts name.upcase
puts name.downcase
puts name.length

In other words, we first address, or mention, the object we want to talk to. We then send a message to the object with the dot (.) by specifying the method name. We also call the method upcase on the string.

Remember: The . is used to call a method on an object.

Imagine the string name is a person we can talk to. We can ask questions by sending them messages, and they’ll respond by sending (returning) something back. The term “sending messages” is used instead of the phrase “calling a method” in object-oriented programming, and specifically in Ruby.

Most methods in Ruby work this way. We ask an object to return a bit of information about itself (such as a string’s length) or a modified (transformed) version of itself (such as a lowercase version of the string).

Remember: Most methods are questions and return a relevant value.

Others modify the object itself, and some have side effects and modify something else. For example, puts and p both output something to the screen. Other methods might save files, send emails, or store things in a database.

Remember: Some methods are commands and change the object or the system (like by saving a file).

Further readings

Take a look at all the methods that the String class defines (response to) on Ruby’s documentation page for this class.