Evgenii Legotckoi
June 29, 2016, 12:59 p.m.

User Guide #20 - Ruby - global variables

A global variable has a name beginning with $. It can be referred to from anywhere in a program. Before initialization, a global variable has the special value nil.

ruby> $foo
   nil
ruby> $foo = 5
   5
ruby> $foo
   5

Global variables should be used sparingly. They are dangerous because they can be written to from anywhere. Overuse of globals can make isolating bugs difficult; it also tends to indicate that the design of a program has not been carefully thought out. Whenever you do find it necessary to use a global variable, be sure to give it a descriptive name that is unlikely to be inadvertently used for something else later (calling it something like $foo as above is probably a bad idea).


One nice feature of a global variable is that it can be traced; you can specify a procedure which is invoked whenever the value of the variable is changed.

ruby> trace_var :$x, proc{print "$x is now ", $x, "\n"}
   nil
ruby> $x = 5
$x is now 5
   5

When a global variable has been rigged to work as a trigger to invoke a procedure whenever changed, we sometimes call it an active variable . For instance, it is useful for keeping a GUI display up to date.

There is a collection of special variables whose names consist of a dollar sign ( $ ) followed by a single character. For example, $$ contains the process id of the ruby interpreter, and is read-only. Here are the major system variables and their meanings:

  • $! - latest error message
  • $@ - location of error
  • $_ - string last read by gets
  • $. - line number last read by interpreter
  • $& - string last matched by regexp
  • $~ - the last regexp match, as an array of subexpressions
  • $ n - the nth subexpression in the last match (same as $~[ n ])
  • $= - case-insensitivity flag
  • $/ - input record separator
  • $\ - output record separator
  • $0 - the name of the ruby script file
  • $* - the command line arguments
  • $$ - interpreter's process ID
  • $? - exit status of last executed child process

In the above, $_ and $~ have local scope. Their names suggest they should be global, but they are much more useful this way, and there are historical reasons for using these names.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html