Ruby/Zmienne instancji: 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:
== Zmienne instancji ==
An instance variable has a name beginning with @, and its scope is confined to whatever object self refers to. Two different objects, even if they belong to the same class, are allowed to have different values for their instance variables. From outside the object, instance variables cannot be altered or even observed (i.e., ruby's instance variables are never public) except by whatever methods are explicitly provided by the programmer. As with globals, instance variables have the nil value until they are initialized.
 
Zmienna instancji ma nazwę zaczynającą się znakiem <tt>@</tt>, a jej zasięg zasięg ograniczony jest tylko do obiektu wskazywanego przez <tt>self</tt>. Dwa różne obiekty, nawet jeśli należą do tej samej klasy, mogą mieć różne wartości swoich zmiennych instancji. Na zewnątrz obiektu zmienne instancji nie mogą być zmienione, ani nawet odczytane (zmienne instancji w Rubim nigdy nie są publiczne), chyba że za pośrednictwem metod wyraźnie dostarczonych przez programistę. Tak jak zmienne globalne, zmienne instancji mają wartość <tt>nil</tt> dopóki nie zostaną zainicjalizowane.
Instance variables do not need to be declared. This indicates a flexible object structure; in fact, each instance variable is dynamically appended to an object when it is first assigned.
 
Zmienne instancji nie muszą być zadeklarowane. Wskazuje to na elastyczną strukturę obiektu. W rzeczywistości, każda zmienna instancji jest dynamicznie dołączana do obiektu w czasie pierwszego przypisania jej wartości.
 
<pre>
ruby> class InstTest
| def set_foo(n)
Linia 22 ⟶ 25:
ruby> i
#<InstTest:0x83678 @foo=2, @bar=4>
</pre>
 
Zauważ, że powyższe <tt>i</tt> nie zwraca wartości <tt>@bar</tt> dopóki nie zostanie wywołana metoda <tt>set_bar</tt>.
Notice above that i does not report a value for @bar until after the set_bar method is invoked.
<noinclude>
{{ProstaNawigacja|spis=Ruby|poprzart=Ruby/Zmienne globalne|poprz=Zmienne globalne|nastart=Ruby/Zmienne lokalne|nast=Zmienne lokalne}}