Defining and Calling Methods in Ruby
Methods are the building blocks of Ruby programs. They let you group related code together, give it a name, and call it whenever you need it. Instead of writing the same code over and over, you define it once in a method and reuse it.
In this tutorial, you’ll learn how to define methods, pass arguments, return values, and use the various Ruby method conventions.
What is a Method?
A method is a named block of code that performs a specific task. Think of it as a reusable recipe: you define the instructions once, then “cook” (call) the method whenever you need the result.
Methods help you:
- Avoid repeating code
- Organize your program into logical pieces
- Make your code easier to read and maintain
- Break complex problems into smaller, manageable parts
Defining a Basic Method
In Ruby, you define a method using the def keyword, followed by the method name, and end to close the definition:
def greet
puts "Hello, World!"
end
To run this method, you call it by name:
greet
# Output: Hello, World!
This is the simplest form of a method—it takes no arguments and returns nothing useful (implicitly returns nil).
Methods with Parameters
Most useful methods accept input in the form of parameters. Parameters are variables that receive values when you call the method:
def greet_person(name)
puts "Hello, #{name}!"
end
greet_person("Alice")
# Output: Hello, Alice!
greet_person("Bob")
# Output: Hello, Bob!
The name parameter is a placeholder that gets replaced with the actual value (“Alice” or “Bob”) when the method runs.
Default Parameter Values
You can provide default values for parameters. These are used when no argument is passed:
def greet_person(name = "Stranger")
puts "Hello, #{name}!"
end
greet_person
# Output: Hello, Stranger!
greet_person("Charlie")
# Output: Hello, Charlie!
Default parameters make methods more flexible—callers can provide custom values or skip arguments entirely.
Returning Values from Methods
Ruby methods can return values using the return keyword, or implicitly return the last evaluated expression:
def add(a, b)
return a + b
end
result = add(3, 5)
puts result
# Output: 8
You can also omit return—Ruby automatically returns the last expression:
def multiply(a, b)
a * b
end
result = multiply(4, 7)
puts result
# Output: 28
Multiple Parameters
Methods can accept any number of parameters:
def introduce(name, age, city)
puts "I am #{name}, #{age} years old, from #{city}."
end
introduce("Diana", 28, "London")
# Output: I am Diana, 28 years old, from London.
Variable-Length Arguments
Ruby supports methods that accept a variable number of arguments using the splat operator (*):
def sum(*numbers)
total = 0
numbers.each { |n| total += n }
total
end
puts sum(1, 2)
# Output: 3
puts sum(1, 2, 3, 4, 5)
# Output: 15
puts sum()
# Output: 0
The *numbers collects all arguments into an array, letting you handle any number of inputs.
Keyword Arguments
Ruby also supports keyword arguments, which are more explicit and self-documenting:
def create_user(name:, email:, age: nil)
{ name: name, email: email, age: age }
end
user = create_user(name: "Eve", email: "eve@example.com")
puts user
# Output: {:name=>"Eve", :email=>"eve@example.com", :age=>nil}
user2 = create_user(name: "Frank", email: "frank@example.com", age: 30)
puts user2
# Output: {:name=>"Frank", :email=>"frank@example.com",:age=>30}
Keyword arguments require the caller to specify parameter names, reducing errors from argument order mistakes.
Method Naming Conventions
Ruby has specific conventions for method names:
- Use snake_case:
calculate_total,user_name - End with a question mark (
?) for methods that return boolean:empty?,valid?,includes? - End with an exclamation mark (
!) for dangerous or mutating methods:save!,update!,chomp!
def empty?
@items.length == 0
end
def save!
raise "Cannot save!" unless valid?
# save logic here
end
Calling Methods
You call a method simply by using its name. Ruby provides several ways to pass arguments:
Positional arguments:
result = add(10, 5)
Keyword arguments:
result = calculate(x: 10, y: 5)
With parentheses (optional):
result = add(10, 5)
result = add 10, 5 # also valid
When to Use Methods
Use methods when you:
- Have code that repeats in multiple places
- Want to give a descriptive name to a block of code
- Need to test individual pieces of functionality
- Want to make your code more readable and maintainable
When Not to Overuse Methods
Avoid creating methods for:
- Trivial one-liners that are clearer inline
- Very specific logic used only once
- Premature optimization—write clear code first, refactor later
Summary
Methods are essential for organizing Ruby code. You’ve learned how to:
- Define basic methods with
defandend - Add parameters and default values
- Return values explicitly or implicitly
- Use variable-length and keyword arguments
- Follow Ruby naming conventions
In the next tutorial, we’ll explore working with strings in Ruby—another fundamental skill for Ruby developers.