Ruby Process Object Resolution _ruby topics

Source: Internet
Author: User
Tags anonymous
We always want to classify unknown events. When it happens, passing a piece of code as a parameter to other methods is the easiest way to do it, which means we want to work with the code like we do with the data.

A new process object can be created by proc:

ruby> Quux = proc {
| print "Quuxquuxquux!!! \ n "
| }
#<proc:0x4017357c>


Now Quux points to an object, and like any other object, it has behavior that can be invoked. In particular, we can execute it using the call method:

Ruby> Quux.call
Quuxquuxquux!!!
Nil


So can quux be used as a parameter to a method?

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 choices for any system signal.

ruby> Inthandler = proc{print "^c was pressed.\n"}
#<proc:0x401730a4>
Ruby> trap "SIGINT", Inthandler
#<proc:0x401735e0>


In general, typing ^c will cause the interpreter to exit. But now a message is printed and the interpreter continues to execute, so you won't lose the job you're working on. (You don't stay in the interpreter forever, you can still exit with exit or press ^d)

The last thing to note before we start the next section is that you don't have to name a process object before you bind a process object to a signal. An equivalent anonymous (anonymous) process object like this

Ruby> trap "SIGINT", proc{print "^c was pressed.\n"}
Nil


or more briefly,

Ruby> trap "SIGINT", ' print ' ^c was pressed.\n '
Nil


This shorthand provides you with a convenient and 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.