Advanced search
Evgenij LegotskojAug. 26, 2016, 3:56 a.m.

RubyUser Guide #28 - Ruby - Nuts and bolts

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

This chapter addresses a few practical issues.

Statement delimiters

Some languages require some kind of punctuation, often a semicolon ( ; ), to end each statement in a program. Ruby instead follows the convention used in shells like sh and csh . Multiple statements on one line must be separated by semicolons, but they are not required at the end of a line; a linefeed is treated like a semicolon. If a line ends with a backslash ( \ ), the linefeed following it is ignored; this allows you to have a single logical line that spans several lines.

Comments

Why write comments? Although well written code tends to be self-documenting, it is often helpful to scribble in the margins, and it can be a mistake to believe that others will be able to look at your code and immediately see it the way you do. Besides, for practical purposes, you yourself are a different person within a few days anyway; which of us hasn't gone back to fix or enhance a program after the passage of time and said, I know I wrote this, but what in blazes does it mean?

Some experienced programmers will point out, quite correctly, that contradictory or outdated comments can be worse than none at all. Certainly, comments shouldn't be a substitute for readable code; if your code is unclear, it's probably also buggy. You may find that you need to comment more while you are learning ruby, and then less as you become better at expressing your ideas in simple, elegant, readable code.

Evgenij LegotskojAug. 26, 2016, 3:52 a.m.

RubyUser Guide #27 - Ruby - Object initialization

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

Our Fruit class from the previous chapter had two instance variables, one to describe the kind of fruit and another to describe its condition. It was only after writing a custom inspect method for the class that we realized it didn't make sense for a piece of fruit to lack those characteristics. Fortunately, ruby provides a way to ensure that instance variables always get initialized.

The initialize method

Whenever Ruby creates a new object, it looks for a method named initialize and executes it. So one simple thing we can do is use an initialize method to put default values into all the instance variables, so the inspect method will have something to say.

ruby> class Fruit
    |   def initialize
    |     @kind = "apple"
    |     @condition = "ripe"
    |   end
    | end   nil
ruby> f4 = Fruit.new   "a ripe apple"
Evgenij LegotskojAug. 26, 2016, 3:21 a.m.

RubyUser Guide #26 - Ruby - Accessors

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

What is an accessor?

We briefly discussed instance variables in an earlier chapter, but haven't done much with them yet. An object's instance variables are its attributes, the things that distinguish it from other objects of the same class. It is important to be able to write and read these attributes; doing so requires methods called attribute accessors . We'll see in a moment that we don't always have to write accessor methods explicitly, but let's go through all the motions for now. The two kinds of accessors are writers and readers .

ruby> class Fruit
    |   def set_kind(k)  # a writer
    |     @kind = k
    |   end
    |   def get_kind     # a reader
    |     @kind
    |   end
    | end   nil
ruby> f1 = Fruit.new   #<Fruit:0xfd7e7c8c>
ruby> f1.set_kind("peach")  # use the writer   "peach"
ruby> f1.get_kind           # use the reader   "peach"
ruby> f1                    # inspect the object   #<Fruit:0xfd7e7c8c @kind="peach">
Evgenij LegotskojAug. 26, 2016, 3:18 a.m.

RubyUser Guide #25 - Ruby - Exception processing: ensure

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

There may be cleanup work that is necessary when a method finishes its work. Perhaps an open file should be closed, buffered data should be flushed, etc. If there were always only one exit point for each method, we could confidently put our cleanup code in one place and know that it would be executed; however, a method might return from several places, or our intended cleanup code might be unexpectedly skipped because of an exception.

begin
  file = open("/tmp/some_file", "w")
  # ... write to the file ...
  file.close
end
Evgenij LegotskojAug. 26, 2016, 3:09 a.m.

RubyUser Guide #24 - Ruby - Exception processing: rescue

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

An executing program can run into unexpected problems. A file that it wants to read might not exist; the disk might be full when it wants to save some data; the user may provide it with some unsuitable kind of input.

ruby> file = open("some_file")ERR: (eval):1:in `open': No such file or directory - some_file

A robust program will handle these situations sensibly and gracefully. Meeting that expectation can be an exasperating task. C programmers are expected to check the result of every system call that could possibly fail, and immediately decide what is to be done:

FILE *file = fopen("some_file", "r");
if (file == NULL) {
  fprintf( stderr, "File doesn't exist.\n" );
  exit(1);
}
bytes_read = fread( buf, 1, bytes_desired, file );
if (bytes_read != bytes_desired ) {
  /* do more error handling here ... */
}
...
Evgenij LegotskojAug. 25, 2016, 3:05 a.m.

RubyUser Guide #23 - Ruby - Class constants

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

A constant has a name starting with an uppercase character. It should be assigned a value at most once. In the current implementation of ruby, reassignment of a constant generates a warning but not an error (the non-ANSI version of eval.rb does not report the warning):

ruby>fluid=30
   30
ruby>fluid=31
   31
ruby>Solid=32
   32
ruby>Solid=33
   (eval):1: warning: already initialized constant Solid
   33
Evgenij LegotskojJuly 10, 2016, 3:03 a.m.

RubyUser Guide #22 - Ruby - Local variables

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

A local variable has a name starting with a lower case letter or an underscore character (_). Local variables do not, like globals and instance variables, have the value nil before initialization:

ruby> $foo
   nil
ruby> @foo
   nil
ruby> foo
ERR: (eval):1: undefined local variable or method `foo' for main(Object)

The first assignment you make to a local variable acts something like a declaration. If you refer to an uninitialized local variable, the ruby interpreter thinks of it as an attempt to invoke a method of that name; hence the error message you see above.

Evgenij LegotskojJuly 10, 2016, 3:01 a.m.

RubyUser Guide #21 - Ruby - Instance variables

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

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.

Evgenij LegotskojJune 29, 2016, 2:59 a.m.

RubyUser Guide #20 - Ruby - global variables

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

A global variable has a name beginning with $. It can be referred to from anywhere in a program. Before initialization, a global variable has the special value nil.

ruby> $foo
   nil
ruby> $foo = 5
   5
ruby> $foo
   5

Global variables should be used sparingly. They are dangerous because they can be written to from anywhere. Overuse of globals can make isolating bugs difficult; it also tends to indicate that the design of a program has not been carefully thought out. Whenever you do find it necessary to use a global variable, be sure to give it a descriptive name that is unlikely to be inadvertently used for something else later (calling it something like $foo as above is probably a bad idea).

Evgenij LegotskojJune 29, 2016, 2:57 a.m.

RubyUser Guide #19 - Ruby - variables

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

Ruby has three kinds of variables, one kind of constant and exactly two pseudo-variables. The variables and the constants have no type. While untyped variables have some drawbacks, they have many more advantages and fit well with ruby's quick and easy philosophy.

Variables must be declared in most languages in order to specify their type, modifiability (i.e., whether they are constants), and scope; since type is not an issue, and the rest is evident from the variable name as you are about to see, we do not need variable declarations in ruby.

The first character of an identifier categorizes it at a glance:

  • $ - global variable
  • @ - instance variable
  • [a-z] или _ - local variable
  • [A-Z] - constant
Timeweb

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
VS

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

  • Result:14points,
  • Rating points-10
VS

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

  • Result:14points,
  • Rating points-10
IP

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

  • Result:10points,
  • Rating points-10
Last comments
A
  • Andrey
  • April 28, 2021, 1:25 a.m.

Django - Tutorial 036. How to add authentication through social networks. VKontakte

после того как дам разрешение для просмотра моего емайл, вот такая ошибка: AuthForbidden at /social-auth/complete/vk-oauth2/ Your credentials aren't allowed Вот сетингс: SOC…
DV

Qt/C++ - Lesson 051. QMediaPlayer – simple audio player

Добрый вечер. Хотел бы получить консультацию по работе с проектом на Mac OS. Открыл проект в QT и собрал его. Проблема в том, что он не воспроизводит треки и их названия зацикленно мелькают в по…
SS

Как соответствовать новым требованиям Google Play

Добрый день. Спасибо вам огромное за вашу статью! только начинаю изучать QT под Андроид 4 дня потратил на то чтобы подобрать версию QT которая наконец то скомпилирует мне на windo…
YA

PyQt5 - Tutorial 009. Using QThread with MoveToThread

Hello. Let's say I want to send some variables to "run" define. How can we do that? I modified your code, I tried something like below, but the GUI is frozen that way. I could not be able to und…
R

Распознавание изображений на Python с помощью TensorFlow и Keras

почему то вместо 50000 обрабатывает по 782 картинки кажду. эпоху
Now discuss on the forum

Потеря данных в сигнал/слот

вопрос решен
M

Qt/QML/Android(navigation button) - Стандартные клавиши навигации Андроид

Здравствуйте, пытаюсь заставить работать стандартную андроид-клавишу "назад", пытался разными способоами, они приведены в закомментированном коде. В том числе использовал https://evileg.com/ru/f…
M

Как включить OpenGL в Adnroid эмуляторе QtCreator

Здравствуйте, у меня работают виртуальные машины с Android, но только в дефолтной был включен OpenGL. Потом я удалил дефолтную, создал новые, а в них OpenGL отключен. Справа на втором скриншоте …

QScrollArea dynamically add QCheckBoxes

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

qml зажатая кнопка мыши в одной MouseArea и сигналы мыши из другой MouseArea

добрый, вы не пробовали отслеживать область видимости мышки через: _mouseArea.containsMouse и когда мышка будет в другой зоне видимости обрабатывать ее состояния?
About
Services
© EVILEG 2015-2021
Recommend hosting TIMEWEB