Skip to content
AgileLogics
6 min read

Methods

Prerequisites: Hashes

A method is a named, reusable block of code that performs a task. You define it once and call it as many times as you like. (Other languages call these functions; in Ruby they're called methods because, technically, they always belong to an object.)

Real-world analogy: a method is a recipe. You write the steps down once, and then just say "make pancakes" whenever you want them.

Syntax

def method_name(parameter)
  # code
end

Example

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

puts greet("Ada")
puts greet("Linus")

Expected output

Hello, Ada!
Hello, Linus!

Line by line:

  • def greet(name) starts a method called greet with one parameter, name — a placeholder for the value you pass in.
  • The last line of a method is its return value, automatically. There's no need to write return.
  • greet("Ada") calls the method, passing "Ada" as the argument.

Naming conventions

  • Method names use snake_case, like variables.
  • A method that answers a yes/no question ends in ?: def adult?(age) = age >= 18.
  • A method with a surprising or "dangerous" side effect ends in !.

That def adult?(age) = age >= 18 form is an endless method — a one-line method with no end, available since Ruby 3.0. Use it only for genuinely short methods.

Common mistakes

  • Calling a method before it's defined in a script. Ruby runs top to bottom, so the def must come first: undefined method 'greet' for main (NoMethodError).
  • Passing the wrong number of arguments: wrong number of arguments (given 0, expected 1) (ArgumentError).

Practice

Write a method area(width, height) that returns the area of a rectangle, and a method square?(width, height) that returns whether the rectangle is a square. Print both for a 4 by 4 rectangle.

Show solution
def area(width, height)
  width * height
end

def square?(width, height) = width == height

puts area(4, 4)
puts square?(4, 4)
16
true