Ruby 简明教程

Ruby - Methods

Ruby 方法与任何其他编程语言中的函数非常类似。Ruby 方法用于将一个或多个可重复的语句捆绑到一个单元中。

Ruby methods are very similar to functions in any other programming language. Ruby methods are used to bundle one or more repeatable statements into a single unit.

方法名应以小写字母开头。如果您以大写字母开始方法名,Ruby 可能认为它是一个常量,因而可能会错误地解析该调用。

Method names should begin with a lowercase letter. If you begin a method name with an uppercase letter, Ruby might think that it is a constant and hence can parse the call incorrectly.

方法应该在调用之前定义,否则 Ruby 将引发一个有关未定义的方法调用的异常。

Methods should be defined before calling them, otherwise Ruby will raise an exception for undefined method invoking.

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 represent a method that accepts parameters like this −

def method_name (var1, var2)
   expr..
end

您可以为参数设置默认值,如果在调用方法时没有传递所需的参数,则将使用该默认值−

You can set default values for the parameters, which will be used if method is called without passing the required parameters −

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

无论何时调用简单方法,都只需按照如下方式编写方法名−

Whenever you call the simple method, you write only the method name as follows −

method_name

然而,在使用参数调用方法时,请按照如下方式编写方法名和参数−

However, when you call a method with parameters, you write the method name along with the parameters, such as −

method_name 25, 30

使用带有参数的方法最重要的问题在于你无论何时调用这样的方法时,都需要记住参数的数目。例如,如果一个方法接收三个参数,而你只传递了两个,那么 Ruby 会显示一条错误信息。

The most important drawback to using methods with parameters is that you need to remember the number of parameters whenever you call such methods. For example, if a method accepts three parameters and you pass only two, then Ruby displays an error.

Example

#!/usr/bin/ruby

def test(a1 = "Ruby", a2 = "Perl")
   puts "The programming language is #{a1}"
   puts "The programming language is #{a2}"
end
test "C", "C++"
test

这会产生以下结果 −

This will produce the following result −

The programming language is C
The programming language is C++
The programming language is Ruby
The programming language is Perl

Return Values from Methods

Ruby 中的每一个方法默认返回一个值。这个返回值将是最后一条语句的值。例如 −

Every method in Ruby returns a value by default. This returned value will be the value of the last statement. For example −

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

这个方法在被调用时,将返回最后声明的变量 k。

This method, when called, will return the last declared variable k.

Ruby return Statement

Ruby 中的 return 语句用于从 Ruby 方法返回一个或多个值。

The return statement in ruby is used to return one or more values from a Ruby Method.

Syntax

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

如果给出了超过两个表达式,则包含这些值的数组将是返回值。如果没有给出表达式,则 nil 将是返回值。

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

Example

return

OR

return 12

OR

return 1,2,3

看一下这个示例 −

Have a look at this example −

#!/usr/bin/ruby

def test
   i = 100
   j = 200
   k = 300
return i, j, k
end
var = test
puts var

这会产生以下结果 −

This will produce the following result −

100
200
300

Variable Number of Parameters

假设你声明了一个需要两个参数的方法,无论何时你调用这个方法时,都需要传递两个参数。

Suppose you declare a method that takes two parameters, whenever you call this method, you need to pass two parameters along with it.

然而,Ruby 允许你声明可处理不定数量的参数的方法。让我们检查一个关于该内容的示例 −

However, Ruby allows you to declare methods that work with a variable number of parameters. Let us examine a sample of this −

#!/usr/bin/ruby

def sample (*test)
   puts "The number of parameters is #{test.length}"
   for i in 0...test.length
      puts "The parameters are #{test[i]}"
   end
end
sample "Zara", "6", "F"
sample "Mac", "36", "M", "MCA"

在这个代码中,你已经声明了一个方法 sample,它接收一个参数 test。然而,这个参数是一个可变参数。这意味着这个参数可以带入任意数量的变量。因此,上述代码将产生以下结果 −

In this code, you have declared a method sample that accepts one parameter test. However, this parameter is a variable parameter. This means that this parameter can take in any number of variables. So, the above code will produce the following result −

The number of parameters is 3
The parameters are Zara
The parameters are 6
The parameters are F
The number of parameters is 4
The parameters are Mac
The parameters are 36
The parameters are M
The parameters are MCA

Class Methods

当一个方法在类定义之外被定义时,这个方法默认被标记为 private。另一方面,在类定义中定义的方法默认被标记为 public。可以通过 Module 的 public 或 private 来更改默认可见性和方法的 private 标记。

When a method is defined outside of the class definition, the method is marked as private by default. On the other hand, the methods defined in the class definition are marked as public by default. The default visibility and the private mark of the methods can be changed by public or private of the Module.

无论何时你想访问类的某个方法时,首先需要实例化这个类。然后,你可以使用该对象来访问类的任何成员。

Whenever you want to access a method of a class, you first need to instantiate the class. Then, using the object, you can access any member of the class.

Ruby 为你提供了一种无需实例化类即可访问方法的方式。让我们看看一个类方法是如何声明和访问的 −

Ruby gives you a way to access a method without instantiating a class. Let us see how a class method is declared and accessed −

class Accounts
   def reading_charge
   end
   def Accounts.return_date
   end
end

看看 return_date 方法是如何声明的,它在类名后接一个点,后面再接方法名。你可以直接按以下方式访问这个类方法 −

See how the method return_date is declared. It is declared with the class name followed by a period, which is followed by the name of the method. You can access this class method directly as follows −

Accounts.return_date

要访问这个方法,不需要创建 Accounts 类的对象。

To access this method, you need not create objects of the class Accounts.

Ruby alias Statement

这为方法或全局变量提供一个别名。别名不能在方法主体中定义。即使方法被重写,别名也会保留方法的当前定义。

This gives alias to methods or global variables. Aliases cannot be defined within the method body. The alias of the method keeps the current definition of the method, even when methods are overridden.

禁止为编号全局变量($1,$2,…​)创建别名。重写内置全局变量可能会导致严重的问题。

Making aliases for the numbered global variables ($1, $2,…​) is prohibited. Overriding the built-in global variables may cause serious problems.

Syntax

alias method-name method-name
alias global-variable-name global-variable-name

Example

alias foo bar
alias $MATCH $&

在这里,我们为 bar 定义了 foo 别名,而 $MATCH 是 $& 的别名

Here we have defined foo alias for bar, and $MATCH is an alias for $&

Ruby undef Statement

这会取消方法的定义。undef 不会出现在方法主体中。

This cancels the method definition. An undef cannot appear in the method body.

通过使用 undef 和 alias,类的接口可以独立于超类进行修改,但请注意,self 对内部方法的调用可能会破坏程序。

By using undef and alias, the interface of the class can be modified independently from the superclass, but notice it may be broke programs by the internal method call to self.

Syntax

undef method-name

Example

要取消定义名为 bar 的方法,请执行以下操作:

To undefine a method called bar do the following −

undef bar