Ruby/Kontrola dostępu: Różnice pomiędzy wersjami
Usunięta treść Dodana treść
Szymon wro (dyskusja | edycje) mNie podano opisu zmian |
Szymon wro (dyskusja | edycje) Nie podano opisu zmian |
||
Linia 1:
==Kontrola dostępu==
Wcześniej powiedzieliśmy, że Ruby nie posiada funkcji, tylko metody. Jednakże jest nieco więcej różnych rodzajów metod. W tym rozdziale przedstawimy sposoby kontroli dostępu.
Rozważmy, co się stanie, gdy zdefiniujemy metodę na samym szczycie hierarchii, nie wewnątrz jakiejkolwiek klasy? Możemy myśleć o takiej metodzie analogicznie jak o funkcji w bardziej tradycyjnym języku, takim jak C.
<pre>
ruby> def square(n)
| n * n
Linia 9 ⟶ 12:
ruby> square(5)
25
</pre>
Our new method would appear not to belong to any class, but in fact ruby gives it to the Object class, which is a superclass of every other class. As a result, any object should now be able to use that method. That turns out to be true, but there's a small catch: it is a private method of every class. We'll discuss some of what this means below, but one consequence is that it may be invoked only in function style, as here:
|