Skip to main content

How to Define a Method in Ruby with def

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

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​

Syntax
def <name>(<parameter>, <parameter>)
<body>
end
PartWhat 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.
endCloses 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:

main.rb, which defines area(width, height) whose body is width * height, and puts area(3, 4) and area(10, 2).

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​

Terminal
ruby main.rb
Output
12
20

A zsh terminal where ruby main.rb prints 12 and 20.

The command is the same in zsh, bash and PowerShell.

Common Mistakes​

MistakeWhat happensDo 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 endUnmatched keyword, missing `end' ?, pointing at the def lineClose every def with end
Calling the method above its defundefined method 'area' for main (NoMethodError)Define methods before the code that calls them

Troubleshooting​

SymptomLikely causeFix
wrong number of arguments (given N, expected M)The call and the definition don't matchPass the number of values the method expects
Unmatched keyword, missing `end' ?A def, if or do without its endAdd 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.