Methods

Package up reusable pieces of code

8 min read

As your programs grow, you will often find yourself writing the same few lines of code again and again. Ruby lets you package up a piece of code and give it a name, so you can reuse it whenever you need it. This reusable package is called a method.

Defining your first method

You create a method using the def keyword, followed by a name you choose, and closed with end.

def greet
  puts "Hello there!"
end

greet

The first part, from def to end, defines the method but does not run it yet. The final line, greet, actually calls the method, which is what makes it run.

Methods that accept information

Methods become much more useful when they can accept information from whoever calls them. These pieces of information are called parameters.

def greet(name)
  puts "Hello, #{name}!"
end

greet("Ava")
greet("Sam")

This prints "Hello, Ava!" and then "Hello, Sam!" The word name inside the parentheses is a placeholder that gets filled in with whatever you pass in when you call the method.

Methods that return a value

Methods can also hand back a result to be used elsewhere, simply by making the result the last line of the method.

def add(a, b)
  a + b
end

total = add(3, 4)
puts total

This prints 7. Ruby automatically returns the value of the last line inside a method, so you do not always need to write return explicitly.

Why methods matter

  • They let you reuse code instead of copying and pasting it.
  • They make your programs easier to read, since a good method name explains what it does.
  • They make fixing bugs easier, since you only need to fix the code in one place.

Good method names usually describe an action, like greet, add, or calculate_total. Clear names make your code almost read like a story.

Quick check

Q1 Which keyword starts a method definition in Ruby?

Q2 If a method's last line is a + b, what does calling the method return?

Want to save your progress? It's free.

Create a free account