Defining Simple Methods

You’ve seen many method invocations in examples throughout this book, and method invocation syntax was described in detail in Method Invocations. Now we turn to the syntax for defining methods. This section explains method definition basics. It is followed by three more sections that cover method names, method parentheses, and method arguments in more detail. These additional sections explain more advanced material and are relevant to both method definition and method invocation.

Methods are defined with the def keyword. This is followed by the method name and an optional list of parameter names in parentheses. The Ruby code that constitutes the method body follows the parameter list, and the end of the method is marked with the end keyword. Parameter names can be used as variables within the method body, and the values of these named parameters come from the arguments to a method invocation. Here is an example method:

# Define a method named 'factorial' with a single parameter 'n'
def factorial(n)
  if n < 1                # Test the argument value for validity
    raise "argument must be > 0"
  elsif n == 1            # If the argument is 1
    1                     # then the value of the method invocation is 1
  else                    # Otherwise, the factorial of n is n times
    n * factorial(n-1)    # the factorial of n-1
  end
end

This code defines a method named factorial. The method has a single parameter named n. The identifier n is used as a variable within the body of the method. This is a recursive method, so the body of the method ...

Get The Ruby Programming Language now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.