Ruby/Domknięcia i obiekty procedurowe: Różnice pomiędzy wersjami

Usunięta treść Dodana treść
Kj (dyskusja | edycje)
m nav
Szymon wro (dyskusja | edycje)
Nie podano opisu zmian
Linia 1:
== Obiekty procedurowe ==
It is often desirable to be able to specify responses to unexpected events. As it turns out, this is most easily done if we can pass blocks of code as arguments to other methods, which means we want to be able to treat code as if it were data.
 
Dobrze jest być w stanie sformułować odpowiedzi na niespodziewane zdarzenia. Jak się okazuje, najłatwiej to osiągnąć, jeśli możemy przekazywać całe bloki kodu jako argumenty do innych metod, to znaczy, że chcemy móc tak traktować kod, jakby to były dane.
A new procedure object is formed using proc:
 
Obiekt procedurowy jest formułowany z użyciem słowa kluczowego <tt>proc</tt>:
 
<pre>
ruby> quux = proc {
| puts "QUUXQUUXQUUX!!!"
| }
#<Proc:0x4017357c>
</pre>
 
To, na co wskazuje <tt>quux</tt> jest obiektem, i jak większość obiektów, posiada zachowanie które może zostać wywołane. Możemy poprosić nasz obiekt aby wykonał je, wywołując jego metodę <tt>call</tt>:
Now what quux refers to is an object, and like most objects, it has behavior that can be invoked. Specifically, we can ask it to execute, via its call method:
 
<pre>
ruby> quux.call
QUUXQUUXQUUX!!!
nil
</pre>
 
Tak więc, po tym wszystkim, czy można użyć <tt>quux</tt> jako argumentu metody? Oczywiście.
So, after all that, can quux be used as a method argument? Sure.
 
<pre>
ruby> def run( p )
| puts "About to call a procedure..."
Linia 27 ⟶ 34:
There: finished.
nil
</pre>
 
Metoda <tt>trap</tt> pozwala nam przypisać dowolną odpowiedź do każdego sygnału.
The trap method lets us assign the response of our choice to any system signal.
 
<pre>
ruby> inthandler = proc{ puts "^C was pressed." }
#<Proc:0x401730a4>
ruby> trap "SIGINT", inthandler
#<Proc:0x401735e0>
</pre>
 
Normalnie naciśnięcie ^C powoduje wyjście z interpretera. Zamiast tego drukowana jest informacja a interpreter kontynuuje swoje działanie, tak więc nie stracisz pracy, którą robiłeś. (Nie jesteś jednak w pułapce interpretera na wieczność. Wciąż możesz wpisać <tt>exit</tt>.)
Normally pressing ^C makes the interpreter quit. Now a message is printed and the interpreter continues running, so you don't lose the work you were doing. (You're not trapped in the interpreter forever; you can still exit by typing exit.)
 
A final note before we move on to other topics: it's not strictly necessary to give a procedure object a name before binding it to a signal. An equivalent anonymous procedure object would look like