Ruby Methods
A method is a named piece of code you can call again and again. Methods keep programs organised: instead of repeating the same lines, you write them once, give them a clear name, and call that name. (Other languages call them functions; in Ruby every function belongs to some object, so they are all "methods".)
Defining and calling a method
A method starts with def, followed by its name, and ends with end:
def welcome
puts "Welcome to the library!"
puts "Opening hours: 9-18"
end
welcome
welcomeWelcome to the library!
Opening hours: 9-18
Welcome to the library!
Opening hours: 9-18
Defining a method doesn't run it — the code runs each time you call it.
Parameters
Values you pass in are received as parameters:
def area(width, height)
width * height
end
def describe_room(name, width, height)
puts "#{name}: #{area(width, height)} m²"
end
describe_room("Kitchen", 4, 3)
describe_room("Hall", 2, 6.5)Kitchen: 12 m²
Hall: 13.0 m²
Calling a method with the wrong number of arguments raises an ArgumentError:
def area(width, height)
width * height
end
begin
area(5)
rescue ArgumentError => e
puts e.message
endwrong number of arguments (given 1, expected 2)
Implicit return
A Ruby method returns the value of its last evaluated expression. You don't need to write return:
def full_name(first, last)
"#{first} #{last}"
end
def even_or_odd(n)
if n.even?
"even"
else
"odd"
end
end
puts full_name("Alan", "Turing")
puts even_or_odd(7)Alan Turing
odd
return is still useful to leave a method early — see the Return Values lesson.
Naming conventions
| Pattern | Meaning | Example |
|---|---|---|
snake_case |
normal method | total_price |
ends with ? |
returns true/false | valid?, empty? |
ends with ! |
dangerous / modifies receiver | save!, sort! |
ends with = |
setter, called with assignment | name= (obj.name = "x") |
def adult?(age)
age >= 18
end
def shout!(text)
text.upcase!
text << "!"
end
p adult?(21)
message = +"careful"
shout!(message)
p messagetrue
"CAREFUL!"
The ! warns the caller: this method changes the object you pass in.
One-line (endless) methods
Since Ruby 3.0, a short method can be written on one line with =:
def square(x) = x * x
def greet(name) = "Hi, #{name}"
def pi = 3.14159
p square(12)
p greet("Ola")
p pi144
"Hi, Ola"
3.14159
Methods are called on objects
Every method has a receiver — the object before the dot. When there's no dot, the receiver is self (the current object). Methods defined at the top level of a script become private methods of main, which is why you can call them anywhere in the file.
p "text".length # receiver: "text"
p [3, 1].sort # receiver: [3, 1]
p self # top-level object
p 5.respond_to?(:+)
p method(:puts).owner4
[1, 3]
main
true
Kernel
puts itself is a method from the Kernel module, available everywhere.
Recursion
A method can call itself. Every recursive method needs a base case that stops the calls:
def factorial(n)
return 1 if n <= 1
n * factorial(n - 1)
end
def fib(n) = n < 2 ? n : fib(n - 1) + fib(n - 2)
p factorial(10)
p (0..10).map { |i| fib(i) }3628800
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Defining methods before using them
Ruby reads a file from top to bottom. A method must be defined before the line that calls it is executed — but inside another method, you can refer to a method defined later, because that body only runs when called.
Tip: Keep methods short and give them names that say what they return or do. A method longer than ~10 lines is often doing two jobs and can be split.
Test yourself
What does a Ruby method return if there is no return statement?
- nil always
- The value of the last evaluated expression
- true
- The first argument
By convention, what does a method name ending in ? return?
- A string
- A true/false value
- nil
- An array
What happens when you call def add(a, b) as add(1)?
- b becomes nil
- It returns 1
- ArgumentError is raised
- b becomes 0