Methods ↑

Methods implement the functionality of your program. Here is a simple method definition:

def one_plus_one
  1 + 1
end

A method definition consists of the def keyword, a method name, the body of the method, return value and the end keyword. When called the method will execute the body of the method. This method returns 2.

Since Ruby 3.0, there is also a shorthand syntax for methods consisting of exactly one expression:

def one_plus_one = 1 + 1

This section only covers defining methods. See also the syntax documentation on calling methods.

Method Names ↑

Method names may be one of the operators or must start a letter or a character with the eighth bit set. It may contain letters, numbers, an _ (underscore or low line) or a character with the eighth bit set. The convention is to use underscores to separate words in a multiword method name:

def method_name
  puts "use underscores to separate words"
end

Ruby programs must be written in a US-ASCII-compatible character set such as UTF-8, ISO-8859-1 etc. In such character sets if the eighth bit is set it indicates an extended character. Ruby allows method names and other identifiers to contain such characters. Ruby programs cannot contain some characters like ASCII NUL (\x00).

The following are examples of valid Ruby methods:

def hello
  "hello"
end

def こんにちは
  puts "means hello in Japanese"
end

Typically method names are US-ASCII compatible since the keys to type them exist on all keyboards.

Method names may end with a ! (bang or exclamation mark), a ? (question mark), or = (equals sign).

The bang methods (! at the end of the method name) are called and executed just like any other method. However, by convention, a method with an exclamation point or bang is considered dangerous. In Ruby’s core library the dangerous method implies that when a method ends with a bang (!), it indicates that unlike its non-bang equivalent, permanently modifies its receiver. Almost always, the Ruby core library will have a non-bang counterpart (method name which does NOT end with !) of every bang method (method name which does end with !) that does not modify the receiver. This convention is typically true for the Ruby core library but may or may not hold true for other Ruby libraries.

Methods that end with a question mark by convention return boolean, but they may not always return just true or false. Often, they will return an object to indicate a true value (or “truthy” value).

Methods that end with an equals sign indicate an assignment method.

class C