Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Ruby / Yukihiro Matsumoto_Programming Ruby.doc
Скачиваний:
122
Добавлен:
06.06.2015
Размер:
2.71 Mб
Скачать

Invoking a Method

[receiver.]name[parameters][block]

[receiver::]name[parameters][block]

parameters

<-

( [param]* [,hashlist][*array][&aProc])

block

<-

{ blockbody}

do blockbodyend

Initial parameters are assigned to the actual arguments of the method. Following these parameters may be a list of key=>valuepairs. These pairs are collected into a single newHashobject and passed as a single parameter.

Following these parameters may be a single parameter prefixed with an asterisk. If this parameter is an array, Ruby replaces it with zero or more parameters corresponding to the elements of the array.

def regular(a, b, *c)

  # ..

end

regular 1, 2, 3, 4

regular(1, 2, 3, 4)

regular(1, *[2, 3, 4])

A block may be associated with a method call using either a literal block (which must start on the same source line as the last line of the method call) or a parameter containing a reference to a ProcorMethodobject prefixed with an ampersand character. Regardless of the presence of a block argument, Ruby arranges for the value of the global functionKernel::block_given? to reflect the availability of a block associated with the call.

aProc   = proc { 99 }

anArray = [ 98, 97, 96 ]

def block

  yield

end

block { }

block do

      end

block(&aProc)

def all(a, b, c, *d, &e)

  puts "a = #{a}"

  puts "b = #{b}"

  puts "c = #{c}"

  puts "d = #{d}"

  puts "block = #{yield(e)}"

end

all('test', 1 => 'cat', 2 => 'dog', *anArray, &aProc)

produces:

a = test

b = {1=>"cat", 2=>"dog"}

c = 98

d = [97, 96]

block = 99

A method is called by passing its name to a receiver. If no receiver is specified, selfis assumed.

The receiver checks for the method definition in its own class and then sequentially in its ancestor classes. The instance methods of included modules act as if they were in anonymous superclasses of the class that includes them. If the method is not found, Ruby invokes the method method_missingin the receiver. The default behavior defined inKernel::method_missing is to report an error and terminate the program.

When a receiver is explicitly specified in a method invocation, it may be separated from the method name using either a period ``.'' or two colons ``::''. The only difference between these two forms occurs if the method name starts with an uppercase letter. In this case, Ruby will assume that areceiver::Thingmethod call is actually an attempt to access a constant calledThingin the receiverunlessthe method invocation has a parameter list between parentheses.

Foo.Bar()         #  method call

Foo.Bar           #  method call

Foo::Bar()        #  method call

Foo::Bar          #  constant access

The return value of a method is the value of the last expression executed.

return [

expr

]*

A returnexpression immediately exits a method. The value of areturnisnilif it is called with no parameters, the value of its parameter if it is called with one parameter, or an array containing all of its parameters if it is called with more than one parameter.

super

super [([

param

]*

[*array

])][

block

]

Within the body of a method, a call to superacts just like a call to that original method, except that the search for a method body starts in the superclass of the object that was found to contain the original method. If no parameters (and no parentheses) are passed tosuper, the original method's parameters will be passed; otherwise, the parameters tosuperwill be passed.

Operator Methods

expr1operator

operatorexpr1

expr1operatorexpr2

If the operator in an operator expression corresponds to a redefinable method (see the Table 18.4 on page 219), Ruby will execute the operator expression as if it had been written

(expr1).operator(expr2)

Attribute Assignment

receiver.attrname=rvalue

When the form receiver.attrnameappears as an lvalue, Ruby invokes a method namedattrname=in the receiver, passingrvalueas a single parameter.

Element Reference Operator

receiver [

expr

]+

receiver [

expr

]+

= rvalue

When used as an rvalue, element reference invokes the method []in the receiver, passing as parameters the expressions between the brackets.

When used as an lvalue, element reference invokes the method []=in the receiver, passing as parameters the expressions between the brackets, followed by thervaluebeing assigned.

Aliasing

alias newNameoldName

creates a new name that refers to an existing method, operator, global variable, or regular expression backreference ($&,$',$', and$+). Local variables, instance variables, class variables, and constants may not be aliased. The parameters toaliasmay be names or symbols.

class Fixnum

  alias plus +

end

1.plus(3)

»

4

alias $prematch $`

"string" =~ /i/

»

3

$prematch

»

"str"

alias :cmd :`

cmd "date"

»

"Sun Nov 25 23:44:19 CST 2001\n"

When a method is aliased, the new name refers to a copy of the original method's body. If the method is subsequently redefined, the aliased name will still invoke the original implementation.

def meth

  "original method"

end

alias original meth

def meth

  "new and improved"

end

meth

»

"new and improved"

original

»

"original method"

Соседние файлы в папке Ruby