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

Usunięta treść Dodana treść
Kj (dyskusja | edycje)
m nav
Szymon wro (dyskusja | edycje)
Nie podano opisu zmian
Linia 1:
Zmienna lokalna posiada nazwę zaczynającą się małą literą lub znakiem podkreślenia (<tt>_</tt>). Zmienne lokalne nie posiadają, w przeciwieństwie do zmiennych globalnych i zmiennych instancji, wartości <tt>nil</tt> przed inicjalizacją:
A local variable has a name starting with a lower case letter or an underscore character (_). Local variables do not, like globals and instance variables, have the value nil before initialization:
 
<pre>
ruby> $foo
nil
Linia 7 ⟶ 8:
ruby> foo
ERR: (eval):1: undefined local variable or method `foo' for main(Object)
</pre>
 
Pierwsze przypisanie, które robisz do zmiennej lokalnej odgrywa rolę jakby deklaracji. Jeżeli Odwołasz się do niezainicjalizowanej zmiennej lokalnej, interpreter Rubiego nie będzie pewny, czy odwołujesz się do nieprawdziwej zmiennej. Możesz, dla przykładu, zrobić błąd w nazwie metody. Dlatego zobaczyłeś raczej ogólną informację o błędzie.
The first assignment you make to a local variable acts something like a declaration. If you refer to an uninitialized local variable, the ruby interpreter cannot be sure whether you are referencing a bogus variable; you might, for example, have misspelled a method name. Hence the rather nonspecific error message you see above.
 
Zazwyczaj zasięgiem zmiennej lokalnej jest jedno z poniższych:
Generally, the scope of a local variable is one of
 
* <tt>proc{ ... }</tt>
* <tt>loop{ ... }</tt>
* <tt>def ... end</tt>
* <tt>class ... end</tt>
* <tt>module ... end</tt>
* cały skrypt (chyba że zastosowano jedno z powyższych)
* the entire script (unless one of the above applies)
 
W następny przykładzie <tt>defined?</tt> jest operatorem, który sprawdza czy identyfikator został zdefiniowany. Zwraca on opis identyfikatora, jeśli jest on zdefiniowany lub, w przeciwnym razie, <tt>nil</tt>. Jak widzisz, zasięg zmiennej <tt>bar</tt> jest ograniczony lokalnie do pętli. Gdy pętla zostaje przerwana <tt>bar</tt> jest niezdefiniowany.
In the next example, defined? is an operator which checks whether an identifier is defined. It returns a description of the identifier if it is defined, or nil otherwise. As you see, bar's scope is local to the loop; when the loop exits, bar is undefined.
 
<pre>
ruby> foo = 44; puts foo; defined?(foo)
44
Linia 27 ⟶ 30:
45
nil
</pre>
 
Procedure objects that live in the same scope share whatever local variables also belong to that scope. Here, the local variable bar is shared by main and the procedure objects p1 and p2: