Ruby Methods

Ruby methods are similar to functions in other programming languages. Ruby methods are used to bundle one or more repeated statements into a single unit.

Method names should begin with a lowercase letter. If you begin a method name with an uppercase letter, Ruby may treat it as a constant, causing the call to be parsed incorrectly.

Methods should be defined before they are called; otherwise, Ruby will raise an undefined method call exception.

Syntax

def method_name [( [arg [= default]]...[, * arg [, &expr ]])] expr.. end

So, you can define a simple method as follows:

def method_name expr.. end

You can define a method that accepts parameters as follows:

def method_name (var1, var2) expr.. end

You can set default values for parameters, which will be used if the required parameters are not passed when the method is called:

def method_name (var1=value1, var2=value2) expr.. end

When you want to call a method, you only need to use the method name, as follows:

method_name

However, when you call a method with parameters, you need to include the parameters when writing the method name, for example:

method_name 25, 30

The biggest disadvantage of using methods with parameters is that you need to remember the number of parameters when calling the method. For example, if you pass only two arguments to a method that accepts three parameters, Ruby will show an error.

Example

#!/usr/bin/ruby # -*- coding: UTF-8 -*- def test(a1="Ruby", a2="Perl") puts "The programming language is #{a1}" puts "The programming language is #{a2}" end test "C", "C++" test

Try it »

The output of the above example is:

编程语言为 C
编程语言为 C++
编程语言为 Ruby
编程语言为 Perl

Returning Values from Methods

Every method in Ruby returns a value by default. The returned value is the value of the last statement. For example:

Example

def test i = 100 j = 10 k = 0 end

When this method is called, the last declared variable k will be returned.

Ruby returnStatement

In Ruby, thereturnstatement is used to return one or more values from a Ruby method.

Syntax

return [expr[`,' expr...]]

If more than two expressions are given, an array containing these values will be the return value. If no expression is given, nil will be the return value.

Example

returnorreturn 12orreturn 1,2,3

Look at the following example:

Example

#!/usr/bin/ruby # -*- coding: UTF-8 -*- def test i = 100 j = 200 k = 300 return i, j, k end var = test puts var

Try it »

The output of the above example is:

100
200
300

Variable Number of Parameters

Suppose you declare a method with two parameters. When you call that method, you also need to pass two arguments.

However, Ruby allows you to declare methods with a variable number of parameters. Let's look at the following example:

Example

#!/usr/bin/ruby # -*- coding: UTF-8 -*- def sample (*test) puts "The number of parameters is #{test.length}" for i in 0...test.length puts "The parameter value is #{test[i]}" end end sample "Zara", "6", "F" sample "Mac", "36", "M", "MCA"

Try it »

In this code, you have declared a method sample that accepts a parameter test. However, this parameter is a variable parameter. This means that the parameter can take a variable number of variables. The output of the above example is:

参数个数为 3
参数值为 Zara
参数值为 6
参数值为 F
参数个数为 4
参数值为 Mac
参数值为 36
参数值为 M
参数值为 MCA

Class Methods

When a method is defined outside a class, it is marked as private by default.privateOn the other hand, if a method is defined inside a class, it is marked as public by default.

The default visibility andprivatemarker can be changed through the module (Module)'spublicorprivatepublic or private.

When you want to access a class's methods, you first need to instantiate the class. Then, using the object, you can access any member of the class.

Ruby provides a way to access methods without instantiating. Let's see how to declare and access class methods:

class Accounts def reading_charge end def Accounts.return_date end end

We already know how the method return_date is declared. It is declared by placing a dot after the class name, followed by the method name. You can directly access class methods, as follows:

Accounts.return_date

To access this method, you do not need to create an object of the class Accounts.

Ruby aliasStatement

This statement is used to alias a method or a global variable. Aliases cannot be defined inside a method body. Even if the method is overridden, the alias of the method preserves the current definition of the method.

Aliasing numbered global variables ($1, $2,...) is forbidden. Overriding built-in global variables may cause serious problems.

Syntax

aliasmethod name method namealiasglobal variable global variable

Example

alias foo bar alias $MATCH $&

Here, we have defined the alias foo for bar, and the alias $MATCH for $&.

Ruby undefStatement

This statement is used to undefine a method.undefIt cannot appear inside a method body.

By usingundefandalias, the class's interface can be modified independently from the parent class, but please note that it may break the program when calling methods inside itself.

undefmethod name

Example

The following example undefines the method namedbarmethod definition:

undef bar
Other Extensions