How to Define a Method in Ruby with def
A method gives a name to a piece of work so you can run it with different values. In Ruby you write one with def, its parameters in brackets, a body and end; it hands back the value of its last line.
Syntax
def <name>(<parameter>, <parameter>)
<body>
end
| Part | What it does |
|---|---|
def <name> | Starts the method definition and names it. |
(<parameter>, ...) | The values the method receives. |
<body> | The code that runs; its last expression is the result. |
end | Closes the definition. |
The Ruby methods documentation: "A method definition consists of the def keyword, a method name, the body of the method, return value and the end keyword."
The Example
The example defines area, which multiplies a width by a height, and calls it for two rectangles.
Prerequisites
- Ruby. This guide uses Ruby 4.0.10.
Step 1: Write the Method
Create a file named main.rb:

def area(width, height)
width * height
end
puts area(3, 4)
puts area(10, 2)
There's no return: width * height is the last expression, so it's the method's result.
Step 2: Run It
ruby main.rb
12
20

The command is the same in zsh, bash and PowerShell.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Passing too few arguments, as in area(3) | wrong number of arguments (given 1, expected 2) (ArgumentError) | Pass every parameter, or give it a default |
Forgetting end | Unmatched keyword, missing `end' ?, pointing at the def line | Close every def with end |
Calling the method above its def | undefined method 'area' for main (NoMethodError) | Define methods before the code that calls them |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
wrong number of arguments (given N, expected M) | The call and the definition don't match | Pass the number of values the method expects |
Unmatched keyword, missing `end' ? | A def, if or do without its end | Add the end |
FAQ
Can a parameter have a default value?
Yes: def area(width, height = 1) lets callers leave height out.
Is there a one-line form?
Yes, for a single expression: def area(width, height) = width * height.
Conclusion
def name(params) ... end defines a method, and its last expression is its result. Call it with name(arguments), passing one value for each parameter without a default.
Additional Resources
- Methods, in the Ruby documentation.
