We always want to classify unknown events. When it happens, passing a piece of code as a parameter to other methods 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.