We always want to classify unknown events. When it happens, pass a piece Code Is the easiest solution, that is, we want to process code like processing data.
A new process object can be created through proc:
Ruby> quux = proc {
| Print "quuxquuxquux !!! \ N"
|}
# <Proc: 0x4017357c>
Now, quux points to an object. Like other objects, it can also be called. In particular, we can use the call method to execute it:
Ruby> quux. Call
Quuxquuxquux !!!
Nil
Can quux be used as a method parameter? Of course.
Ruby> def run (P)
| Print "about to call a procedure... \ n"
| P. Call
| Print "there: Finished. \ n"
| End
Nil
Ruby> RUN quux
About to call a procedure...
Quuxquuxquux !!!
There: finished.
Nil
The trap method allows us to make our own choice for any system signal.
Ruby> inthandler = proc {print "^ C was pressed. \ n "}
# <Proc: 0x401730a4>
Ruby> trap "SIGINT", inthandler
# <Proc: 0x401735e0>
Generally, hitting ^ C will cause the interpreter to exit. but now a piece of information is printed out, and the interpreter continues to execute, so you will not lose the job in progress. (You will not stay in the interpreter forever. You can still exit with exit or press ^ d)
Finally, before starting the next section, we should also note that before binding a process object to a signal, it is not necessary to name this process object. an equivalent anonymous (anonymous) process object is like this
Ruby> trap "SIGINT", Proc {print "^ C was pressed. \ n "}
Nil
Or in a simpler way,
Ruby> trap "SIGINT", 'print "^ C was pressed. \ n "'
Nil
This short form provides you with a convenient and more readable way to write a small anonymous process.