Ruby Methods

A method in Ruby is a set of instructions grouped together to perform a specific task.

Here's a simple example of methods. You can read the rest of the tutorial to learn more.

Example

# Define a method named 'greet'
def greet
  puts "Hello"
end

# Call the method
greet

# Output: Hello

Here, greet is a method that prints "Hello" when called.


Defining a Method

To create a method in Ruby, you use the def keyword followed by the method name.

def method_name
  # Code to run
end

You then call the method later in the code by using the method name:

# Call the method to execute it
method_name

Example

Let's create a method named say_goodbye and call it for execution:

def say_goodbye
  puts "Goodbye!"
end

# Call the method
say_goodbye

# Output: Goodbye!

Here, we created a method named say_goodbye that displays a message. The method is only executed when we call it later in the program.

The image below shows how the method is defined:

Method Definition
Method Definition

Method Parameters

Methods can accept inputs, known as parameters, to perform tasks based on different values.

def method_name(parameter)
  # Use the parameter
end

Example: Method Parameters

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

greet("Alice")
greet("Ruby")

Output

Hello, Alice!
Hello, Ruby!

Here, the method greet takes a parameter name. Then, we called the method by passing "Alice" and "Ruby" as values to the parameter.

Here's how this program works:

Method Call Parameter Value Method Output
greet("Alice") "Alice" Hello, Alice!
greet("Ruby") "Ruby" Hello, Ruby!

Default Parameters

In Ruby, default parameters allow you to assign a default value to a method argument.

So, if you call the method without providing an argument, Ruby will use the default value. For example,

# Method with a default parameter
def greet(name = "Guest")
  puts "Hello, #{name}!"
end

# Call method without passing an argument
greet

# Call method by passing an argument
greet("Alice")

Output

Hello, Guest!
Hello, Alice!

Here, the parameter name has a default value "Guest". We then called the method twice — first without passing an argument, and then by passing an argument.

Here's how this program works:

Method Call Argument Value Method Output
greet "Guest" Hello, Guest!
greet("Alice") "Alice" Hello, Alice!

Calling Methods

In Ruby, there are two ways to call a method, depending on whether it has parameters or not.

Calling a method without parameters

If the method doesn't take any input, you can call it just by writing its name. For example,

def greet
  puts "Good Morning"
end

greet

# Output: Good Morning

Calling a method with parameters

If the method requires input (parameters), pass the values inside parentheses. For example,

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

greet("Sam")

# Output: Hello, Sam

Note: You can call methods without parentheses in Ruby, like greet "Sam", but using parentheses (e.g., greet("Sam")) is clearer and recommended.


Return Values

You can use the return keyword to send a result back from a method. For example,

def add(a, b)
  return a + b
end

puts add(2, 3)

# Output: 5

Here, the method returned the sum of a and b, which is 5.

Note: Methods can return values of different types, like strings, numbers, booleans, etc. They can also return no value, like the greet method we previously coded.

Implicit Return in Ruby

If you omit the return keyword, Ruby will still return the result of the last executed line in the method. For example,

def add(a, b)
  a + b
end

puts add(2, 3)

# Output: 5

Here, Ruby automatically returns a + b even if return is not written. This is known as implicit return.


Method Scope

The scope of a method is that part of the program where the method and its variables can be used.

For now, just remember these two important things:

1. A method cannot access local variables defined outside it.

# Variable defined outside the method
name = "Alice"

def greet
  # Attempt to access name variable
  puts "Hello, #{name}!"
end

greet

Output

NameError: undefined local variable or method 'name' for main:Object#greet

Here, the name variable is defined outside the greet method. So, trying to access that variable inside greet will result in an error.

2. A method's local variables only exist inside the method.

def greet
  name = "Alice"
  puts "Hello, #{name}!"
end

# Invalid: 'name' variable only exists inside greet method
puts name

Output

NameError: undefined local variable or method 'name' for main

Here, the name variable is defined inside the greet method. So, the variable only exists inside the scope of greet.

That's why trying to access name outside greet will result in an error.


Frequently Asked Question

How should you name methods in Ruby?

Ruby follows some common naming conventions for maintaining clean and consistent code:

  • Method names are written in snake_case, like say_hello or calculate_total.
  • Avoid starting method names with an uppercase letter, as those are used for classes and constants.

Ruby also uses special characters at the end of method names for specific meanings:

  • A method ending with a ?, like empty? or even?, usually returns a true or false value.
  • A method that ends in ! (like sort!) usually modifies the object it's called on. Use them carefully!
Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges