User Guide #18 - Ruby - procedure objects

procedure objects, Ruby, ruby lesson, ruby уроки, user guide, процедурные объекты, руководство пользователя

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 call :

ruby> quux = proc {
    |   print "QUUXQUUXQUUX!!!\n"
    | }
   #<Proc:0x4017357c>

Now what quux refers to is an object, and like most objects, it has behavior that can be evoked. Specifically, we can ask it to execute, via its call method:

ruby> quux.call
QUUXQUUXQUUX!!!
   nil

So, after all that, can quux be used as a method argument? Sure.

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 lets us assign the response of our choice to any system signal.

ruby> inthandler = proc{ print "^C was pressed.\n" }
   #<Proc:0x401730a4>
ruby> trap "SIGINT", inthandler
   #<Proc:0x401735e0>

Normally pressing Ctrl+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 exit or pressing Ctrl+D )

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

ruby> trap "SIGINT", proc{ print "^C was pressed.\n" }
   nil

or more compactly still,

ruby> trap "SIGINT", 'print "^C was pressed.\n"'
   nil

This abbreviated form provides some convenience and readability when you write small anonymous procedures.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.
Support the author Donate

Comments

Only authorized users can post comments.
Please, Log in or Sign up
Donate

Hello, Dear Users of EVILEG!!!

If the site helped you, then support the development of the site financially, please.

You can do it by following ways:

Thank you, Evgenii Legotckoi

p
Feb. 17, 2020, 2:41 p.m.
pstMem

C++ - Тест 003. Условия и циклы

  • Result:85points,
  • Rating points6
z
Feb. 17, 2020, 6:02 a.m.
zet

C++ - Test 006. Enumerations

  • Result:80points,
  • Rating points4
z
Feb. 17, 2020, 5:49 a.m.
zet

C++ - Test 001. The first program and data types

  • Result:80points,
  • Rating points4
Last comments
Feb. 17, 2020, 3:22 a.m.
Evgenij Legotskoj

Добрый день. Это кастомный тег, помещается в файл, который находится в каталоге templatetags myapp/ templatetags/ myapp.py
B
Feb. 16, 2020, 1:36 p.m.
BahaMeirman

Добрый вечер! Монжно по подробней о теге get_companion? ссылка не работает.
Feb. 16, 2020, 9:35 a.m.
Evgenij Legotskoj

Добрый день. На GitHub исходники, можете посмотреть в официальном репозитории
B
Feb. 16, 2020, 9:29 a.m.
BahaMeirman

Здравстсвуйте Евгений, непонятно мне где эти исходники найти?
Now discuss on the forum
Feb. 22, 2020, 1:05 p.m.
BlinCT

Всем привет. Для моей приложухи требуется доступ к хедерам дял чтения данных, но к ним имеет доступ рут, без него чтение не происходит. Но как я слышал можно вроде через dbus или polki…
VZ
Feb. 21, 2020, 5:19 a.m.
Vladimir Zhitkovsky

void sendImage(int sessid, int type, int dest, int format, QString imgBase64Data){ QNetworkRequest request; request.setUrl(QUrl(ipAddress + "ctlapi/cmd=preparereportimg&sessid=…
Feb. 20, 2020, 2:40 p.m.
mkdir

Здравствуйте! Пишу игру - 2D платформер в среде Qt. Имею не очень много опыта в разработке. Подскажите, как можно реализовать ситуацию, где QGraphicScene больше, чем QGraphicView и надо двигать …
Feb. 20, 2020, 7:12 a.m.
Mihailll

Вот так похоже можно https://doc.qt.io/qt-5/qtpurchasing-index.html
IP
Feb. 20, 2020, 1:24 a.m.
Igor' Poroshin

QSqlQuery query("SELECT CONCAT("#", LPAD(HEX(`t`.RGB), 6, 0)) FROM table AS t");query.exec(); while (query.next()) { QColor(query.value(0).toString()); }
EVILEG
About
Services
© EVILEG 2015-2019
Recommend hosting TIMEWEB