Ruby/Zmienne globalne: Różnice pomiędzy wersjami

Usunięta treść Dodana treść
Szymon wro (dyskusja | edycje)
Nie podano opisu zmian
Szymon wro (dyskusja | edycje)
Nie podano opisu zmian
Linia 1:
== Zmienne globalne ==
 
Zmienna globalna posiada nazwę zaczynającą się znakiem <tt>$</tt>. Można się do niej odwołać z dowolnego punktu programu. Przed inicjalizacją Azmienna globalglobalna variablema hasspecjalną a name beginning with $. It can be referred to from anywhere in a program. Before initialization, a global variable has the special valuewartość: <tt>nil</tt>.
 
<pre>
ruby> $foo
nil
Linia 9 ⟶ 10:
ruby> $foo
5
</pre>
 
Zmienne globalne powinny być używane oszczędnie. Są one niebezpieczne, ponieważ mogą być zapisane z dowolnego miejsca programu. Nadmierne użycie zmiennych globalnych może sprawić, że izolowanie błędów będzie trudne, a ponadto może wskazywać, że projekt programu nie został gruntownie przemyślany. Ilekroć uznasz za niezbędne użycie zmiennej globalnej, upewnij się, że dasz jej opisową nazwę która nie będzie skłaniać do użycia jej potem niezgodnie z twoimi intencjami. Nazwanie jej np. <tt>$foo</tt> będzie prawdopodobnie złym pomysłem.
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).
 
Jedną z przyjemnych cech zmiennych globalnych jest to, że mogą być śledzone. Możesz określić procedurę, która będzie wywoływana za każdym razme, gdy wartość zmiennej ulegnie zmianie.
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.
 
<pre>
ruby> trace_var :$x, proc{puts "$x is now #{$x}"}
nil
Linia 19 ⟶ 22:
$x is now 5
5
</pre>
 
Gdy zmienna globalna 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 might be 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: