Evgenij LegotskojJune 27, 2016, 1:43 a.m.

User Guide #15 - Ruby - access control

Earlier, we said that ruby has no functions, only methods. However there is more than one kind of method. In this chapter we introduce access controls .

Consider what happens when we define a method in the "top level", not inside a class definition. We can think of such a method as analogous to a function in a more traditional language like C.

ruby> def square(n)
    |   n * n
    | end
ruby> square(5)

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:

ruby> class Foo
    |   def fourth_power_of(x)
    |     square(x) * square(x)
    |   end
    | end
ruby> Foo.new.fourth_power_of 10

We are not allowed to explicitly apply the method to an object:

ruby> "fish".square(5)
ERR: (eval):1: private method `square' called for "fish":String

This rather cleverly preserves ruby's pure-OO nature (functions are still object methods, but the receiver is self implicitly) while providing functions that can be written just as in a more traditional language.

A common mental discipline in OO programming, which we have hinted at in an earlier chapter, concerns the separation of specification and implementation , or what tasks an object is supposed to accomplish and how it actually accomplishes them. The internal workings of an object should be kept generally hidden from its users; they should only care about what goes in and what comes out, and trust the object to know what it is doing internally. As such it is often helpful for classes to have methods that the outside world does not see, but which are used internally (and can be improved by the programmer whenever desired, without changing the way users see objects of that class). In the trivial example below, think of engine as the invisible inner workings of the class.

ruby> class Test
    |   def times_two(a)
    |     print a," times two is ",engine(a),"\n"
    |   end
    |   def engine(b)
    |     b*2
    |   end
    |   private:engine  # this hides engine from users
    | end
ruby> test = Test.new
ruby> test.engine(6)
ERR: (eval):1: private method `engine' called for #<Test:0x4017181c>
ruby> test.times_two(6)
6 times two is 12.

We might have expected test.engine(6) to return 12, but instead we learn that engine is inaccessible when we are acting as a user of a Test object. Only other Test methods, such as times_two , are allowed to use engine . We are required to go through the public interface, which consists of the times_two method. The programmer who is in charge of this class can change engine freely (here, perhaps by changing b*2 to b+b , assuming for the sake of argument that it improved performance) without affecting how the user interacts with Test objects. This example is of course much too simple to be useful; the benefits of access controls become more clear only when we begin to create more complicated and interesting classes.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.
Support the author Donate


Only authorized users can post comments.
Please, Log in or Sign up

Let me recommend you the excellent hosting on which EVILEG is located.

For many years, Timeweb has been proving his stability.

For projects on Django I recommend VDS hosting

View Hosting

C++ - Тест 003. Условия и циклы

  • Result:0points,
  • Rating points-10

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
  • Mili
  • Feb. 18, 2021, 8:22 a.m.

C++ - Тест 003. Условия и циклы

  • Result:50points,
  • Rating points-4
Last comments
  • t1m4
  • Feb. 24, 2021, 1:56 a.m.

Django - Tutorial 052. Redefining a User Model

В данном случае я заходил под superuser но все равно не появлялись эти поля

Django - Tutorial 001. Deploying a site on Django + PostgreSQL + Gunicorn + Nginx

Поднял сервис с помощью systemd, вот по этому мануалу: https://habr.com/ru/post/501414/
  • t1m4
  • Feb. 23, 2021, 6:11 a.m.

Django - Tutorial 052. Redefining a User Model

А как дать ему эти права?

Django - Tutorial 001. Deploying a site on Django + PostgreSQL + Gunicorn + Nginx

Всё по мануалу выше, буква в букву. gunicorn mysite.wsgi:application server { listen 80; server_name; access_log /var/log/nginx/example.log; locat…
Now discuss on the forum

нужна помощь с проектом qt c++

дали задание, на несколько дней. собираюсь делать, но хотел бы получить помощь более опытных людей, чтобы подкорректировать себя и подстраховаться. каким образом это можно сделать? …

QScrollArea dynamically add QCheckBoxes

Всё правильно. Это просто спамер, который отправился в вечный бан.

При рендере тайлов появляется buffer reallocation

upd. с помощью double commander в сырцах OpenStreetMap плагина нашёл такую функцию size_t CoordBuffer::PushCoord(double x, double y) { if (usedPoints>=bufferSize) { buff…

Сигналы и слоты в PyQt5

Решение стало следующим: после конвертации файла Ui из QtDesigner мне никак не выгодно продолжать работать в этом же файле, т.к. я постоянно продолжаю дорабатывать интерфейс, а его поведение я о…

Получение даты сборки программы

Проблему решил так: В .pro файле: VERSION = 1.2.3DEFINES += APP_VERSION=\\\"$$VERSION\\\"#Формирование даты и времени сборки (меняется при полной пересборке проекта)win32:{BLD_DATE=…
© EVILEG 2015-2020
Recommend hosting TIMEWEB