Ruby/Справочник/Proc: различия между версиями

Содержимое удалено Содержимое добавлено
Новая: ==Класс Proc== <tt>Proc</tt> objects are blocks of code that have been bound to a set of local variables. Once bound, the code may be called in different contexts and still access t...
 
Нет описания правки
Строка 1:
==Класс Proc==
Объекты <tt>Proc</tt> являются блоками кода, которые связаны с локальными переменными. Блок кода может быть выполнен в другом контексте.
<tt>Proc</tt> objects are blocks of code that have been bound to a set of local variables. Once bound, the code may be called in different contexts and still access those variables.
<code>def gen_times(factor)
return Proc.new {|n| n*factor }
Строка 25:
Proc.new =&gt; </tt><tt>a_proc </tt>
----
Создает новый объект класса <tt>Proc</tt> и запоминает в нем текущий контекст. <tt>Proc::new</tt> может быть вызван без блока только в пределах метода к которому прицеплен блок (во время вызова). В этом случае блок будет преобразован в объект класса <tt>Proc</tt>.
Creates a new <tt>Proc</tt> object, bound to the current context. <tt>Proc::new</tt> may be called without a block only within a method with an attached block, in which case that block is converted to the <tt>Proc</tt> object.
<code>def proc_from
Proc.new
Строка 33:
===Proc#=====
----
<tt>prc == other_proc =&gt; true orили false</tt>
----
ReturnВозвращает <tt>true</tt>, ifесли <i>prc</i> is the same object asи <i>other_proc</i>, or--- ifодин theyи тот же объект, areили bothесли procsоба withблока theимеют sameодинаковое bodyтело.
===Proc#[]===
----
Строка 41:
prc[params,...] =&gt; obj</tt>
----
Выполняет блок, присваивая параметрам блока значения <i>params</i> и остальных переменных, обозначенных троеточием. Выдает предупреждение, если блок ожидает лишь одно значение, а ему передается больше (тем не менее, он преобразует список параметров в массив и попытается выполнить блок).
Invokes the block, setting the block's parameters to the values in <i>params</i> using something close to method calling semantics. Generates a warning if multiple values are passed to a proc that expects just one (previously this silently converted the parameters to an array).
Для блоков, создаваемых с использованием <tt>Kernel.proc</tt>, генерируется ошибка если число параметров передаваемых в блок превышает число параметров объявленных во время его создания. Для блоков, созданных при помощи <tt>Proc.new</tt>, дополнительные параметры просто отбрасываются.
For procs created using <tt>Kernel.proc</tt>, generates an error if the wrong number of parameters are passed to a proc with multiple parameters. For procs created using <tt>Proc.new</tt>, extra parameters are silently discarded.
Возвращает значение последнего вычисленного выражения в блоке. Смотри еще <tt>Proc#yield</tt>.
Returns the value of the last expression evaluated in the block. See also <tt>Proc#yield</tt>.
<code>a_proc = Proc.new {|a, *b| b.collect {|i| i*a }}
a_proc.call(9, 1, 2, 3) #=> [9, 18, 27]
Строка 49:
a_proc = Proc.new {|a,b| a}
a_proc.call(1,2,3)</code>
<i>producesрезультат:</i>
<code>prog.rb:5: wrong number of arguments (3 for 2) (ArgumentError)
from prog.rb:4:in `call'
from prog.rb:5</code>
 
===Proc#arity===
(еще известен как call)===Proc#arity===
----
<tt>prc.arity - =&gt; fixnum</tt>
----
Возвращает количество аргументов, которые могут быть восприняты блоком. Если блок объявлен без указания аргументов, то возвращает 0. Если число агрументов точно равно n, то возвращает n. Если блок имеет оциональный аргумент, то возвращает -n-1, где n --- количество обязательных аргументов. Блок <tt>proc</tt> без аргументов обычно содержит <tt>||</tt> вместо аргументов.
Returns the number of arguments that would not be ignored. If the block is declared to take no arguments, returns 0. If the block is known to take exactly n arguments, returns n. If the block has optional arguments, return -n-1, where n is the number of mandatory arguments. A <tt>proc</tt> with no argument declarations is the same a block declaring <tt>||</tt> as its arguments.
<code>Proc.new {}.arity #=&gt; 0
Proc.new {||}.arity #=> 0
Строка 69 ⟶ 70 :
<tt>prc.binding =&gt; binding</tt>
----
ReturnsВозвращает theобъект bindingкласса associated<tt>Binding</tt> ассоциированный withс <i>prc</i>. Note thatНапример, <tt>Kernel#eval</tt> acceptsпринимает either aобъекты <tt>Proc</tt> or aили <tt>Binding</tt> object asв itsкачестве secondвторого parameterаргумента.
<code>def fred(param)
proc {}
Строка 82 ⟶ 83 :
prc[params,...] =&gt; obj</tt>
----
Выполняет блок, присваивая параметрам блока значения <i>params</i> и остальных переменных, обозначенных троеточием. Выдает предупреждение, если блок ожидает лишь одно значение, а ему передается больше (тем не менее, он преобразует список параметров в массив и попытается выполнить блок).
Invokes the block, setting the block's parameters to the values in <i>params</i> using something close to method calling semantics. Generates a warning if multiple values are passed to a proc that expects just one (previously this silently converted the parameters to an array).
Для блоков, создаваемых с использованием <tt>Kernel.proc</tt>, генерируется ошибка если число параметров передаваемых в блок превышает число параметров объявленных во время его создания. Для блоков, созданных при помощи <tt>Proc.new</tt>, дополнительные параметры просто отбрасываются.
For procs created using <tt>Kernel.proc</tt>, generates an error if the wrong number of parameters are passed to a proc with multiple parameters. For procs created using <tt>Proc.new</tt>, extra parameters are silently discarded.
Возвращает значение последнего вычисленного выражения в блоке. Смотри еще <tt>Proc#yield</tt>.
Returns the value of the last expression evaluated in the block. See also <tt>Proc#yield</tt>.
<code>a_proc = Proc.new {|a, *b| b.collect {|i| i*a }}
a_proc.call(9, 1, 2, 3) #=> [9, 18, 27]
Строка 94 ⟶ 95 :
from prog.rb:4:in `call'
from prog.rb:5</code>
 
===Proc#clone===
(еще известен как [])===Proc#clone===
----
<tt>prc.clone() =&gt; other_proc</tt>
----
Создает копию блока <tt>prc</tt>.
MISSING: documentation
===Proc#dup===
----
<tt>prc.dup() =&gt; other_proc</tt>
----
Создает копию блока <tt>prc</tt>.
MISSING: documentation
===Proc#to_proc===
----
<tt>prc.to_proc - =&gt; prc</tt>
----
Часть сооглашения о преобразованиии других объектов в объекты класса <tt>Proc</tt>. Внутри класса <tt>Proc</tt> он просто возвращает сам себя.
Part of the protocol for converting objects to <tt>Proc</tt> objects. Instances of class <tt>Proc</tt> simply return themselves.
===Proc#to_s===
----
<tt>prc.to_s =&gt; string</tt>
----
Возвращает строку с уникальным идентификатором для <tt>prc</tt>, вместе с указателем на место, где блок был объявлен.
Shows the unique identifier for this proc, along with an indication of where the proc was defined.