User Guide #12 - Ruby - classes

class, Ruby, ruby lesson, ruby уроки, user guide, класс, руководство пользователя

The real world is filled by objects, and we can classify them. For example, a very small child is likely to say "bow-wow" when seeing a dog, regardless of the breed; we naturally see the world in terms of these categories.

In OO programming terminology, a category of objects like "dog" is called a class , and some specific object belonging to a class is called an instance of that class.

Generally, to make an object in ruby or any other OO language, first one defines the characteristics of a class, then creates an instance. To illustrate the process, let's first define a simple Dog class.

ruby> class Dog
    |   def speak
    |     print "Bow Wow\n"
    |   end
    | end
   nil

In ruby, a class definition is a region of code between the keywords class and end. A def inside this region begins the definition of a method of the class, which as we discussed in the previous chapter, corresponds to some specific behavior for objects of that class.

Now that we have defined a Dog class, we can use it to make a dog:

ruby> pochi = Dog.new
   #<Dog:0xbcb90>

We have made a new instance of the class Dog , and have given it the name pochi. The new method of any class makes a new instance. Because pochi is a Dog according to our class definition, it has whatever properties we decided a Dog should have. Since our idea of Dog -ness was very simple, there is just one trick we can ask pochi to do.

ruby> pochi.speak
Bow Wow
   nil

Making a new instance of a class is sometimes called instantiating that class. We need to have a dog before we can experience the pleasure of its conversation; we can't merely ask the Dog class to bark for us.

ruby> Dog.speak
ERR: (eval):1: undefined method `speak' for Dog:class

It makes no more sense than trying to eat the concept of a sandwich .

On the other hand, if we want to hear the sound of a dog without getting emotionally attached, we can create (instantiate) an ephemeral, temporary dog, and coax a little noise out of it before it disappears.

ruby> (Dog.new).speak   # or more commonly, Dog.new.speak
Bow Wow
   nil

"Wait," you say, "what's all this about the poor fellow disappearing afterwards?" It's true: if we don't bother to give it a name (as we did for pochi ), ruby's automatic garbage collection decides it is an unwanted stray dog, and mercilessly disposes of it. Really it's okay, you know, because we can make all the dogs we want.

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

Comments

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

Hello, Dear Users of EVILEG!!!

If the site helped you, then support the development of the site financially, please.

You can do it by following ways:

Thank you, Evgenii Legotckoi

p
Feb. 17, 2020, 2:41 p.m.
pstMem

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

  • Result:85points,
  • Rating points6
z
Feb. 17, 2020, 6:02 a.m.
zet

C++ - Test 006. Enumerations

  • Result:80points,
  • Rating points4
z
Feb. 17, 2020, 5:49 a.m.
zet

C++ - Test 001. The first program and data types

  • Result:80points,
  • Rating points4
Last comments
Feb. 17, 2020, 3:22 a.m.
Evgenij Legotskoj

Добрый день. Это кастомный тег, помещается в файл, который находится в каталоге templatetags myapp/ templatetags/ myapp.py
B
Feb. 16, 2020, 1:36 p.m.
BahaMeirman

Добрый вечер! Монжно по подробней о теге get_companion? ссылка не работает.
Feb. 16, 2020, 9:35 a.m.
Evgenij Legotskoj

Добрый день. На GitHub исходники, можете посмотреть в официальном репозитории
B
Feb. 16, 2020, 9:29 a.m.
BahaMeirman

Здравстсвуйте Евгений, непонятно мне где эти исходники найти?
Now discuss on the forum
Feb. 22, 2020, 1:05 p.m.
BlinCT

Всем привет. Для моей приложухи требуется доступ к хедерам дял чтения данных, но к ним имеет доступ рут, без него чтение не происходит. Но как я слышал можно вроде через dbus или polki…
VZ
Feb. 21, 2020, 5:19 a.m.
Vladimir Zhitkovsky

void sendImage(int sessid, int type, int dest, int format, QString imgBase64Data){ QNetworkRequest request; request.setUrl(QUrl(ipAddress + "ctlapi/cmd=preparereportimg&sessid=…
Feb. 20, 2020, 2:40 p.m.
mkdir

Здравствуйте! Пишу игру - 2D платформер в среде Qt. Имею не очень много опыта в разработке. Подскажите, как можно реализовать ситуацию, где QGraphicScene больше, чем QGraphicView и надо двигать …
Feb. 20, 2020, 7:12 a.m.
Mihailll

Вот так похоже можно https://doc.qt.io/qt-5/qtpurchasing-index.html
IP
Feb. 20, 2020, 1:24 a.m.
Igor' Poroshin

QSqlQuery query("SELECT CONCAT("#", LPAD(HEX(`t`.RGB), 6, 0)) FROM table AS t");query.exec(); while (query.next()) { QColor(query.value(0).toString()); }
EVILEG
About
Services
© EVILEG 2015-2019
Recommend hosting TIMEWEB