Methods

Download ruby eBook

Introduction

Functions in Ruby provide organized, reusable code to preform a set of actions. Functions simplify the coding process, prevent redundant logic, and make code easier to follow. This topic describes the declaration and utilization of functions, arguments, parameters, yield statements and scope in Ruby.

Remarks

A method is a named block of code, associated with one or more objects and generally identified by a list of parameters in addition to the name.

def hello(name)
  "Hello, #{name}"
end

A method invocation specifies the method name, the object on which it is to be invoked (sometimes called the receiver), and zero or more argument values that are assigned to the named method parameters. The value of the last expression evaluated in the method becomes the value of the method invocation expression.

hello("World")
# => "Hello, World"

When the receiver is not explicit, it is self.

self
# => main

self.hello("World")
# => "Hello, World"

As explained in the Ruby Programming Language book, many languages distinguish between functions, which have no associated object, and methods, which are invoked on a receiver object. Because Ruby is a purely object-oriented language, all methods are true methods and are associated with at least one object.

Overview of Method Parameters

TypeMethod SignatureCall ExampleAssignments
Requireddef fn(a,b,c)fn(2,3,5)a=2, b=3, c=5
Variadicdef fn(*rest)fn(2,3,5)rest=[2, 3, 5]
Defaultdef fn(a=0,b=1)fn(2,3)a=2, b=3
Keyworddef fn(a:0,b:1)fn(a:2,b:3)a=2, b=3

These argument types can be combined in virtually any way you can imagine to create variadic functions. The minimum number of arguments to the function will equal the amount of required arguments in the signature. Extra arguments will be assigned to default parameters first, then to the *rest parameter.

TypeMethod SignatureCall ExampleAssignments
R,D,V,Rdef fn(a,b=1,*mid,z)fn(2,97)a=2, b=1, mid=[], z=97
fn(2,3,97)a=2, b=3, mid=[], z=97
fn(2,3,5,97)a=2, b=3, mid=[5], z=97
fn(2,3,5,7,97)a=2, b=3, mid=[5,7], z=97
R,K,Kdef fn(a,g:6,h:7)fn(2)a=2, g=6, h=7
fn(2,h:19)a=2, g=6, h=19
fn(2,g:17,h:19)a=2, g=17, h=19
VKdef fn(**ks)fn(a:2,g:17,h:19)ks={a:2, g:17, h:19}
fn(four:4,five:5)ks={four:4, five:5}

Related Examples

Stats

237 Contributors: 16
Wednesday, May 10, 2017
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook