Advanced search


Aug. 26, 2016, 3:56 a.m.

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.


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.


Aug. 26, 2016, 3:52 a.m.

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 =   "a ripe apple"


Aug. 26, 2016, 3:21 a.m.

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: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">


Aug. 26, 2016, 3:18 a.m.

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.

  file = open("/tmp/some_file", "w")
  # ... write to the file ...


Aug. 26, 2016, 3:09 a.m.

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" );
bytes_read = fread( buf, 1, bytes_desired, file );
if (bytes_read != bytes_desired ) {
  /* do more error handling here ... */


Aug. 25, 2016, 3:05 a.m.

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):

   (eval):1: warning: already initialized constant Solid


July 10, 2016, 3:03 a.m.

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
ruby> @foo
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.


July 10, 2016, 3:01 a.m.

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.


June 29, 2016, 2:59 a.m.

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
ruby> $foo = 5
ruby> $foo

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).


June 29, 2016, 2:57 a.m.

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

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

April 1, 2020, 8:03 a.m.
Dmitry Kozhinov

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

  • Result:40points,
  • Rating points-8
March 30, 2020, 12:47 p.m.

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

  • Result:60points,
  • Rating points-1
March 29, 2020, 12:14 p.m.

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

  • Result:71points,
  • Rating points1
Last comments
April 3, 2020, 8:06 a.m.
Konstantin Grudnitskiy

Я надеюсь вы уже разобрались в чем дело, но если вдруг нет, то проблема состоит в том, что вы пытаетесь запустить программу из интерпретатора питона. Файл это уже готова…
April 3, 2020, 6:18 a.m.
Konstantin Grudnitskiy

>>> text = 'hello world'>>> ' '.join(word for word in text.split()[:-1])'hello'>>> def remove_last_word(text):... return text and ' '.join(word for word in text.s…
March 27, 2020, 2:40 p.m.
Evgenij Legotskoj

Добрый день. В конце пятой статьи скачать можете.
March 27, 2020, 2:28 p.m.
mkdir _

Здравствуйте, а можно, пожалуйста, ссылку на целые исходники, если есть?
March 27, 2020, 4:36 a.m.
Evgenij Legotskoj

Скорее всего также, как и для установки всех остальных переменых в CMake, через использование set
Now discuss on the forum
April 5, 2020, 5:09 a.m.

Попробуйте CQtDeployer или windeployqt.
April 5, 2020, 2:35 a.m.

Так работает console.log(textEmail.text) var str = textEmail.text; var n =^((([0-9A-Za-z]{1}[-0-9A-z\.]{1,}[0-9A-Za-z]{1})|([0-9А-Яа-я]{1}[-0-9А-я\.]{1,}[…
April 3, 2020, 12:53 p.m.

Само собою на компе этого незаметно.
April 3, 2020, 8:48 a.m.

Евгений, добрый день. Спасибо!
April 3, 2020, 7:52 a.m.

да вроде много чего установленно, если неправильный путь указать то же самое, пробовал запустить видео через плей лист (по примерам из док)и из него назад путь взять, не получилось
© EVILEG 2015-2019
Recommend hosting TIMEWEB