Ruby process Object Parsing

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.