User Guide #11 - Ruby - methods

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

What is a method? In OO programming, we don't think of operating on data directly from outside an object; rather, objects have some understanding of how to operate on themselves (when asked nicely to do so). You might say we pass messages to an object, and those messages will generally elicit some kind of an action or meaningful reply. This ought to happen without our necessarily knowing or caring how the object really works inside. The tasks we are allowed to ask an object to perform (or equivalently, the messages it understands) are that object's methods .

In ruby, we invoke a method of an object with dot notation (just as in C++ or Java). The object being talked to is named to the left of the dot.

ruby> "abcdef".length

Intuitively, this string object is being asked how long it is . Technically, we are invoking the length method of the object "abcdef".

Other objects may have a slightly different interpretation of length , or none at all. Decisions about how to respond to a message are made on the fly, during program execution, and the action taken may change depending on what a variable refers to.

ruby> foo = "abc"
ruby> foo.length
ruby> foo = ["abcde", "fghij"]
   ["abcde", "fghij"]
ruby> foo.length

What we mean by length can vary depending on what object we are talking about. The first time we ask foo for its length in the above example, it refers to a simple string, and there can only be one sensible answer. The second time, foo refers to an array, and we might reasonably think of its length as either 2, 5, or 10; but the most generally applicable answer is of course 2 (the other kinds of length can be figured out if wished).

ruby> foo[0].length
ruby> foo[0].length + foo[1].length

The thing to notice here is that an array knows something about what it means to be an array . Pieces of data in ruby carry such knowledge with them, so that the demands made on them can automatically be satisfied in the various appropriate ways. This relieves the programmer from the burden of memorizing a great many specific function names, because a relatively small number of method names, corresponding to concepts that we know how to express in natural language, can be applied to different kinds of data and the results will be what we expect. This feature of OO programming languages is called polymorphism .

When an object receives a message that it does not understand, an error is "raised":

ruby> foo = 5
ruby> foo.length
ERR: (eval):1: undefined method `length' for 5(Fixnum)

So it is necessary to know what methods are acceptable to an object, though we need not know how the methods are processed.

If arguments are given to a method, they are generally surrounded by parentheses,

object.method(arg1, arg2)

but they can be omitted if doing so does not cause ambiguity.

object.method arg1, arg2

There is a special variable self in ruby; it refers to whatever object calls a method. This happens so often that for convenience the " self." may be omitted from method calls from an object to itself:


is the same as


What we would think of traditionally as a function call is just this abbreviated way of writing method invocations by self. This makes ruby what is called a pure object oriented language. Still, functional methods behave quite similarly to the functions in other programming languages for the benefit of those who do not grok how function calls are really object methods in ruby. We can speak of functions as if they were not really object methods if we want to.

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

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

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

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

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

C++ - Test 006. Enumerations

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

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/
Feb. 16, 2020, 1:36 p.m.

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

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

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

Всем привет. Для моей приложухи требуется доступ к хедерам дял чтения данных, но к ним имеет доступ рут, без него чтение не происходит. Но как я слышал можно вроде через dbus или polki…
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.

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

Вот так похоже можно
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 ( { QColor(query.value(0).toString()); }
© EVILEG 2015-2019
Recommend hosting TIMEWEB