Methods¶↑
Methods implement the functionality of your program. Here is a simple method definition:
defone_plus_one1+1end
A method definition consists of thedef keyword, a method name, the body of the method,return value and theend keyword. When called the method will execute the body of the method. This method returns2.
Since Ruby 3.0, there is also a shorthand syntax for methods consisting of exactly one expression:
defone_plus_one =1+1
This section only covers defining methods. See also thesyntax 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:
defmethod_nameputs"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:
defhello"hello"enddefこんにちは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 justtrue orfalse. 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.
classCdefattr@attrenddefattr=(val)@attr =valendendc =C.newc.attr#=> nilc.attr =10# calls "attr=(10)"c.attr#=> 10
Assignment methods can not be defined using the shorthand syntax.
These are method names for the various Ruby operators. Each of these operators accepts only one argument. Following the operator is the typical use or name of the operator. Creating an alternate meaning for the operator may lead to confusion as the user expects plus to add things, minus to subtract things, etc. Additionally, you cannot alter the precedence of the operators.
+add
-subtract
*multiply
**power
/divide
%modulus division,
String#%&AND
^XOR (exclusive OR)
>>right-shift
<<left-shift, append
==equal
!=not equal
===case equality. See
Object#====~pattern match. (Not just for regular expressions)
!~does not match
<=>comparison aka spaceship operator. See
Comparable<less-than
<=less-than or equal
>greater-than
>=greater-than or equal
To define unary methods minus and plus, follow the operator with an@ as in+@:
classCdef-@puts"you inverted this object"endendobj =C.new-obj# prints "you inverted this object"
The@ is needed to differentiate unary minus and plus operators from binary minus and plus operators.
You can also follow tilde and not (!) unary methods with@, but it is not required as there are no binary tilde and not operators.
Unary methods accept zero arguments.
Additionally, methods for element reference and assignment may be defined:[] and[]= respectively. Both can take one or more arguments, and element reference can take none.
classCdef[](a,b)putsa+benddef[]=(a,b,c)putsa*b+cendendobj =C.newobj[2,3]# prints "5"obj[2,3] =4# prints "10"
Return Values¶↑
By default, a method returns the last expression that was evaluated in the body of the method. In the example above, the last (and only) expression evaluated was the simple sum1 + 1. Thereturn keyword can be used to make it explicit that a method returns a value.
defone_plus_onereturn1+1end
It can also be used to make a method return before the last expression is evaluated.
deftwo_plus_tworeturn2+21+1# this expression is never evaluatedend
Note that for assignment methods the return value will be ignored when using the assignment syntax. Instead, the argument will be returned:
defa=(value)return1+valueendp(self.a =5)# prints 5
The actual return value will be returned when invoking the method directly:
psend(:a=,5)# prints 6
Scope¶↑
The standard syntax to define a method:
defmy_method# ...end
adds the method to a class. You can define an instance method on a specific class with theclass keyword:
classCdefmy_method# ...endend
A method may be defined on another object. You may define a “class method” (a method that is defined on the class, not an instance of the class) like this:
classCdefself.my_method# ...endend
However, this is simply a special case of a greater syntactical power in Ruby, the ability to add methods to any object. Classes are objects, so adding class methods is simply adding methods to the Class object.
The syntax for adding a method to an object is as follows:
greeting ="Hello"defgreeting.broadenself+", world!"endgreeting.broaden# returns "Hello, world!"
self is a keyword referring to the current object under consideration by the compiler, which might make the use ofself in defining a class method above a little clearer. Indeed, the example of adding ahello method to the classString can be rewritten thus:
defString.hello"Hello, world!"end
A method defined like this is called a “singleton method”.broaden will only exist on the string instancegreeting. Other strings will not havebroaden.
Overriding¶↑
When Ruby encounters thedef keyword, it doesn’t consider it an error if the method already exists: it simply redefines it. This is calledoverriding. Rather like extending core classes, this is a potentially dangerous ability, and should be used sparingly because it can cause unexpected results. For example, consider this irb session:
>> "43".to_i=> 43>> class String>> def to_i>> 42>> end>> end=> nil>> "43".to_i=> 42
This will effectively sabotage any code which makes use of the methodString#to_i to parse numbers from strings.
Arguments¶↑
A method may accept arguments. The argument list follows the method name:
defadd_one(value)value+1end
When called, the user of theadd_one method must provide an argument. The argument is a local variable in the method body. The method will then add one to this argument and return the value. If given1 this method will return2.
The parentheses around the arguments are optional:
defadd_onevaluevalue+1end
The parentheses are mandatory in shorthand method definitions:
# OKdef add_one(value) = value + 1# SyntaxErrordef add_one value = value + 1
Multiple arguments are separated by a comma:
defadd_values(a,b)a+bend
When called, the arguments must be provided in the exact order. In other words, the arguments are positional.
Default Values¶↑
Arguments may have default values:
defadd_values(a,b =1)a+bend
The default value does not need to appear first, but arguments with defaults must be grouped together. This is ok:
defadd_values(a =1,b =2,c)a+b+cend
This will raise a SyntaxError:
def add_values(a = 1, b, c = 1) a + b + cend
Default argument values can refer to arguments that have already been evaluated as local variables, and argument values are always evaluated left to right. So this is allowed:
defadd_values(a =1,b =a)a+bendadd_values# => 2
But this will raise aNameError (unless there is a method namedb defined):
defadd_values(a =b,b =1)a+bendadd_values# NameError (undefined local variable or method `b' for main:Object)
Array Decomposition¶↑
You can decompose (unpack or extract values from) anArray using extra parentheses in the arguments:
defmy_method((a,b))pa:a,b:bendmy_method([1,2])
This prints:
{:a=>1,:b=>2}If the argument has extra elements in theArray they will be ignored:
defmy_method((a,b))pa:a,b:bendmy_method([1,2,3])
This has the same output as above.
You can use a* to collect the remaining arguments. This splits anArray into a first element and the rest:
defmy_method((a,*b))pa:a,b:bendmy_method([1,2,3])
This prints:
{:a=>1,:b=>[2,3]}The argument will be decomposed if it responds to to_ary. You should only define to_ary if you can use your object in place of anArray.
Use of the inner parentheses only uses one of the sent arguments. If the argument is not anArray it will be assigned to the first argument in the decomposition and the remaining arguments in the decomposition will benil:
defmy_method(a, (b,c),d)pa:a,b:b,c:c,d:dendmy_method(1,2,3)
This prints:
{:a=>1,:b=>2,:c=>nil,:d=>3}You can nest decomposition arbitrarily:
defmy_method(((a,b),c))# ...end
Array/Hash Argument¶↑
Prefixing an argument with* causes any remaining arguments to be converted to an Array:
defgather_arguments(*arguments)pargumentsendgather_arguments1,2,3# prints [1, 2, 3]
The array argument must appear before any keyword arguments.
It is possible to gather arguments at the beginning or in the middle:
defgather_arguments(first_arg,*middle_arguments,last_arg)pmiddle_argumentsendgather_arguments1,2,3,4# prints [2, 3]
The array argument will capture aHash as the last entry if keywords were provided by the caller after all positional arguments.
defgather_arguments(*arguments)pargumentsendgather_arguments1,a:2# prints [1, {:a=>2}]
However, this only occurs if the method does not declare any keyword arguments.
defgather_arguments_keyword(*positional,keyword:nil)ppositional:positional,keyword:keywordendgather_arguments_keyword1,2,three:3#=> raises: unknown keyword: three (ArgumentError)
Also, note that a bare* can be used to ignore arguments:
defignore_arguments(*)end
You can also use a bare* when calling a method to pass the arguments directly to another method:
defdelegate_arguments(*)other_method(*)end
Keyword Arguments¶↑
Keyword arguments are similar to positional arguments with default values:
defadd_values(first:1,second:2)first+secondend
Arbitrary keyword arguments will be accepted with**:
defgather_arguments(first:nil,**rest)pfirst,restendgather_argumentsfirst:1,second:2,third:3# prints 1 then {:second=>2, :third=>3}
When calling a method with keyword arguments the arguments may appear in any order. If an unknown keyword argument is sent by the caller, and the method does not accept arbitrary keyword arguments, anArgumentError is raised.
To require a specific keyword argument, do not include a default value for the keyword argument:
defadd_values(first:,second:)first+secondendadd_values# ArgumentError (missing keywords: first, second)add_values(first:1,second:2)# => 3
When mixing keyword arguments and positional arguments, all positional arguments must appear before any keyword arguments.
Also, note that** can be used to ignore keyword arguments:
defignore_keywords(**)end
You can also use** when calling a method to delegate keyword arguments to another method:
defdelegate_keywords(**)other_method(**)end
To mark a method as accepting keywords, but not actually accepting keywords, you can use the**nil:
defno_keywords(**nil)end
Calling such a method with keywords or a non-empty keyword splat will result in anArgumentError. This syntax is supported so that keywords can be added to the method later without affected backwards compatibility.
If a method definition does not accept any keywords, and the**nil syntax is not used, any keywords provided when calling the method will be converted to aHash positional argument:
defmeth(arg)argendmeth(a:1)# => {:a=>1}
Block Argument¶↑
The block argument is indicated by& and must come last:
defmy_method(&my_block)my_block.call(self)end
Most frequently the block argument is used to pass a block to another method:
defeach_item(&block)@items.each(&block)end
You are not required to give a name to the block if you will just be passing it to another method:
defeach_item(&)@items.each(&)end
If you are only going to call the block and will not otherwise manipulate it or send it to another method, usingyield without an explicit block parameter is preferred. This method is equivalent to the first method in this section:
defmy_methodyieldselfend
Argument Forwarding¶↑
Since Ruby 2.7, an all-arguments forwarding syntax is available:
defconcrete_method(*positional_args,**keyword_args,&block) [positional_args,keyword_args,block]enddefforwarding_method(...)concrete_method(...)endforwarding_method(1,b:2) {puts3 }#=> [[1], {:b=>2}, #<Proc:...skip...>]
Calling with forwarding... is available only in methods defined with....
def regular_method(arg, **kwarg) concrete_method(...) # Syntax errorend
Since Ruby 3.0, there can be leading arguments before... both in definitions and in invocations (but in definitions they can be only positional arguments without default values).
defrequest(method,path,**headers)puts"#{method.upcase} #{path} #{headers}"enddefget(...)request(:GET,...)# leading argument in invokingendget('http://ruby-lang.org','Accept'=>'text/html')# Prints: GET http://ruby-lang.org {"Accept"=>"text/html"}deflogged_get(msg,...)# leading argument in definitionputs"Invoking #get: #{msg}"get(...)endlogged_get('Ruby site','http://ruby-lang.org')# Prints:# Invoking #get: Ruby site# GET http://ruby-lang.org {}
Note that omitting parentheses in forwarding calls may lead to unexpected results:
deflog(...)puts...# This would be treated as `puts()...',# i.e. endless range from puts resultendlog("test")# Prints: warning: ... at EOL, should be parenthesized?# ...and then empty line
Exception Handling¶↑
Methods have an implied exception handling block so you do not need to usebegin orend to handle exceptions. This:
defmy_methodbegin# code that may raise an exceptionrescue# handle exceptionendend
May be written as:
defmy_method# code that may raise an exceptionrescue# handle exceptionend
Similarly, if you wish to always run code even if an exception is raised, you can useensure withoutbegin andend:
defmy_method# code that may raise an exceptionensure# code that runs even if previous code raised an exceptionend
You can also combinerescue withensure and/orelse, withoutbegin andend:
defmy_method# code that may raise an exceptionrescue# handle exceptionelse# only run if no exception raised aboveensure# code that runs even if previous code raised an exceptionend
If you wish to rescue an exception for only part of your method, usebegin andend. For more details see the page onexception handling.