Calling Methods

Calling a method sends a message to an object so it can perform some work.

In ruby you send a message to an object like this:

my_method()

Note that the parenthesis are optional:

my_method

Except when there is difference between using and omitting parentheses, this document uses parenthesis when arguments are present to avoid confusion.

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

Receiver

self is the default receiver. If you don’t specify any receiverself will be used. To specify a receiver use.:

my_object.my_method

This sends themy_method message tomy_object. Any object can be a receiver but depending on the method’s visibility sending a message may raise aNoMethodError.

You may also use:: to designate a receiver, but this is rarely used due to the potential for confusion with:: for namespaces.

Chaining Method Calls

You can “chain” method calls by immediately following one method call with another.

This example chains methodsArray#append andArray#compact:

a = [:foo,'bar',2]a1 = [:baz,nil,:bam,nil]a2 =a.append(*a1).compacta2# => [:foo, "bar", 2, :baz, :bam]

Details:

You can chain methods that are in different classes. This example chains methodsHash#to_a andArray#reverse:

h = {foo:0,bar:1,baz:2}h.to_a.reverse# => [[:baz, 2], [:bar, 1], [:foo, 0]]

Details:

Safe Navigation Operator

&., called “safe navigation operator”, allows to skip method call when receiver isnil. It returnsnil and doesn’t evaluate method’s arguments if the call is skipped.

REGEX =/(ruby) is (\w+)/i"Ruby is awesome!".match(REGEX).values_at(1,2)# => ["Ruby", "awesome"]"Python is fascinating!".match(REGEX).values_at(1,2)# NoMethodError: undefined method `values_at' for nil:NilClass"Python is fascinating!".match(REGEX)&.values_at(1,2)# => nil

This allows to easily chain methods which could return empty value. Note that&. skips only one next call, so for a longer chain it is necessary to add operator on each level:

"Python is fascinating!".match(REGEX)&.values_at(1,2).join(' - ')# NoMethodError: undefined method `join' for nil:NilClass"Python is fascinating!".match(REGEX)&.values_at(1,2)&.join(' - ')# => nil

Arguments

There are three types of arguments when sending a message, the positional arguments, keyword (or named) arguments and the block argument. Each message sent may use one, two or all types of arguments, but the arguments must be supplied in this order.

All arguments in ruby are passed by reference and are not lazily evaluated.

Each argument is separated by a,:

my_method(1,'2',:three)

Arguments may be an expression, a hash argument:

'key'=>value

or a keyword argument:

key: value

Hash and keyword arguments must be contiguous and must appear after all positional arguments, but may be mixed:

my_method('a'=>1,b:2,'c'=>3)

Positional Arguments

The positional arguments for the message follow the method name:

my_method(argument1,argument2)

In many cases, parenthesis are not necessary when sending a message:

my_methodargument1,argument2

However, parenthesis are necessary to avoid ambiguity. This will raise aSyntaxError because ruby does not know which method argument3 should be sent to:

method_one argument1, method_two argument2, argument3

If the method definition has a*argument extra positional arguments will be assigned toargument in the method as anArray.

If the method definition doesn’t include keyword arguments, the keyword or hash-type arguments are assigned as a single hash to the last argument:

defmy_method(options)poptionsendmy_method('a'=>1,b:2)# prints: {'a'=>1, :b=>2}

If too many positional arguments are given, anArgumentError is raised.

Default Positional Arguments

When the method defines default arguments you do not need to supply all the arguments to the method. Ruby will fill in the missing arguments in-order.

First we’ll cover the simple case where the default arguments appear on the right. Consider this method:

defmy_method(a,b,c =3,d =4)p [a,b,c,d]end

Herec andd have default values which ruby will apply for you. If you send only two arguments to this method:

my_method(1,2)

You will see ruby print[1, 2, 3, 4].

If you send three arguments:

my_method(1,2,5)

You will see ruby print[1, 2, 5, 4]

Ruby fills in the missing arguments from left to right.

Ruby allows default values to appear in the middle of positional arguments. Consider this more complicated method:

defmy_method(a,b =2,c =3,d)p [a,b,c,d]end

Hereb andc have default values. If you send only two arguments to this method:

my_method(1,4)

You will see ruby print[1, 2, 3, 4].

If you send three arguments:

my_method(1,5,6)

You will see ruby print[1, 5, 3, 6].

Describing this in words gets complicated and confusing. I’ll describe it in variables and values instead.

First1 is assigned toa, then6 is assigned tod. This leaves only the arguments with default values. Since5 has not been assigned to a value yet, it is given tob andc uses its default value of3.

Keyword Arguments

Keyword arguments follow any positional arguments and are separated by commas like positional arguments:

my_method(positional1,keyword1:value1,keyword2:value2)

Any keyword arguments not given will use the default value from the method definition. If a keyword argument is given that the method did not list, and the method definition does not accept arbitrary keyword arguments, anArgumentError will be raised.

Keyword argument value can be omitted, meaning the value will be fetched from the context by the name of the key

keyword1 ='some value'my_method(positional1,keyword1:)# ...is the same asmy_method(positional1,keyword1:keyword1)

Be aware that when method parenthesis are omitted, too, the parsing order might be unexpected:

my_methodpositional1,keyword1:some_other_expression# ...is actually parsed asmy_method(positional1,keyword1:some_other_expression)

Block Argument

The block argument sends a closure from the calling scope to the method.

The block argument is always last when sending a message to a method. A block is sent to a method usingdo ... end or{ ... }:

my_methoddo# ...end

or:

my_method {# ...}

do end has lower precedence than{ } so:

method_1method_2 {# ...}

Sends the block tomethod_2 while:

method_1method_2do# ...end

Sends the block tomethod_1. Note that in the first case if parentheses are used the block is sent tomethod_1.

A block will accept arguments from the method it was sent to. Arguments are defined similar to the way a method defines arguments. The block’s arguments go in| ... | following the openingdo or{:

my_methoddo|argument1,argument2|# ...end

Block Local Arguments

You may also declare block-local arguments to a block using; in the block arguments list. Assigning to a block-local argument will not override local arguments outside the block in the caller’s scope:

defmy_methodyieldselfendplace ="world"my_methoddo|obj;place|place ="block"puts"hello #{obj} this is #{place}"endputs"place is: #{place}"

This prints:

hellomainthisisblockplaceis:world

So theplace variable in the block is not the sameplace variable as outside the block. Removing; place from the block arguments gives this result:

hellomainthisisblockplaceis:block

Unpacking Positional Arguments

Given the following method:

defmy_method(argument1,argument2,argument3)end

You can turn anArray into an argument list with* (or splat) operator:

arguments = [1,2,3]my_method(*arguments)

or:

arguments = [2,3]my_method(1,*arguments)

Both are equivalent to:

my_method(1,2,3)

The* unpacking operator can be applied to any object, not only arrays. If the object responds to a to_a method, this method is called, and is expected to return anArray, and elements of this array are passed as separate positional arguments:

classNamedefinitialize(name)@name =nameenddefto_a =@name.split(' ')endname =Name.new('Jane Doe')p(*name)# prints separate values:#   Jane#   Doe

If the object doesn’t have a to_a method, the object itself is passed as one argument:

classNamedefinitialize(name)@name =nameendendname =Name.new('Jane Doe')p(*name)# Prints the object itself:#   #<Name:0x00007f9d07bca650 @name="Jane Doe">

This allows to handle one or many arguments polymorphically. Note also thatnil hasNilClass#to_a defined to return an empty array, so conditional unpacking is possible:

my_method(*(some_argumentsifsome_condition?))

If to_a method exists and does not return anArray, it would be an error on unpacking:

classNamedefinitialize(name)@name =nameenddefto_a =@nameendname =Name.new('Jane Doe')p(*name)#  can't convert Name to Array (Name#to_a gives String) (TypeError)

You may also use the** (described next) to convert aHash into keyword arguments.

If the number of objects in theArray do not match the number of arguments for the method, anArgumentError will be raised.

If the splat operator comes first in the call, parentheses must be used to avoid an ambiguity of interpretation as an unpacking operator or multiplication operator. In this case, Ruby issues a warning in verbose mode:

my_method*arguments# warning: '*' interpreted as argument prefixmy_method(*arguments)# no warning

Unpacking Keyword Arguments

Given the following method:

defmy_method(first:1,second:2,third:3)end

You can turn aHash into keyword arguments with the** (keyword splat) operator:

arguments = {first:3,second:4,third:5 }my_method(**arguments)

or:

arguments = {first:3,second:4 }my_method(third:5,**arguments)

Both are equivalent to:

my_method(first:3,second:4,third:5)

The** unpacking operator can be applied to any object, not only hashes. If the object responds to a to_hash method, this method is called, and is expected to return anHash, and elements of this hash are passed as keyword arguments:

classNamedefinitialize(name)@name =nameenddefto_hash = {first:@name.split(' ').first,last:@name.split(' ').last}endname =Name.new('Jane Doe')p(**name)# Prints: {name: "Jane", last: "Doe"}

Unlike* operator,** raises an error when used on an object that doesn’t respond to to_hash. The one exception isnil, which doesn’t explicitly define this method, but is still allowed to be used in** unpacking, not adding any keyword arguments.

Again, this allows for conditional unpacking:

my_method(some:params,**(some_extra_paramsifpass_extra_params?))

Like* operator,** raises an error when the object responds to to_hash, but it doesn’t return aHash.

If the method definition uses the keyword splat operator to gather arbitrary keyword arguments, they will not be gathered by*:

defmy_method(*a,**kw)parguments:a,keywords:kwendmy_method(1,2,'3'=>4,five:6)

Prints:

{:arguments=>[1,2],:keywords=>{'3'=>4,:five=>6}}

Proc to Block Conversion

Given a method that use a block:

defmy_methodyieldselfend

You can convert a proc or lambda to a block argument with the& (block conversion) operator:

argument =proc {|a|puts"#{a.inspect} was yielded" }my_method(&argument)

If the block conversion operator comes first in the call, parenthesis must be used to avoid a warning:

my_method&argument# warningmy_method(&argument)# no warning

Method Lookup

When you send a message, Ruby looks up the method that matches the name of the message for the receiver. Methods are stored in classes and modules so method lookup walks these, not the objects themselves.

Here is the order of method lookup for the receiver’s class or moduleR:

IfR is a class with a superclass, this is repeated withR‘s superclass until a method is found.

Once a match is found method lookup stops.

If no match is found this repeats from the beginning, but looking formethod_missing. The defaultmethod_missing isBasicObject#method_missing which raises aNameError when invoked.

If refinements (an experimental feature) are active, the method lookup changes. See therefinements documentation for details.