DEV Community

Annie Huynh
Annie Huynh

Posted on

Ruby Methods

A method is a reusable section of code written to perform a specific task in a program.

Reasons to divide programs into methods:

  1. If something goes wrong in your code, it's much easier to find and fix bugs if you've organized your program well. Assigning specific tasks to separate methods helps with this organization.

  2. Makes your program less redundant and code more reusable - not only can you repeatedly use the same method in a single program without rewriting it each time, but you can even use the method in another program.

Method Syntax

Methods are defined using the keyword def.

There are three parts:

  1. The header, which includes the def keyword, the name of the method, and any arguments the method takes.

  2. The body, which is the code block that describes the procedures the method carries out. The body is indented two spaces by convention.

  3. The method ends with the end keyword.

Parameters and Arguments

If a method takes arguments, we say it accepts or expects those arguments.

The argument is the piece of code you actually put between the method's parentheses when you call it, and the parameter is the name you put between the method's parentheses when you define it.


Splat arguments are arguments preceded by an asterisk. this tells the program that the method can receive one or more arguments.

The syntax for defining a method that has multiple arguments is as follows:

def what_up(greeting, *friends)
  friends.each { |friend| puts "#{greeting}, #{friend}!" }

what_up("What up", "Ian", "Zoe", "Zenas", "Eleanor")
Enter fullscreen mode Exit fullscreen mode

The "*" symbol before the friends parameter, indicates that this method can receive multiple friend arguments.


Return, hands us back a value.

The return keyword is used to specify the result that the method should produce. When you call the method, it "returns" this result, which you can use then use in other parts of your program.

If you replace return with print in a method, the method will output something into the console, but it won't produce a result that you can use in your code. So if you need to use the result of a method elsewhere in your program, you need to use return, not print.

Top comments (0)