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.
A new procedure object is formed using
| puts "QUUXQUUXQUUX!!!"
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
So, after all that, can
quux be used as a method
| puts "About to call a procedure..."
| puts "There: finished."
ruby> run quux
About to call a procedure...
trap method lets us assign the response of our choice
to any system signal.
ruby> trap "SIGINT", inthandler
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
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
or more compactly still,
This abbreviated form provides some convenience and readability when you write small anonymous procedures.