diff --git a/ru/documentation/faq/1/index.md b/ru/documentation/faq/1/index.md index 18e1fedd72..3cee0d38e0 100644 --- a/ru/documentation/faq/1/index.md +++ b/ru/documentation/faq/1/index.md @@ -1,73 +1,73 @@ --- layout: page -title: "Official Ruby FAQ" +title: "Официальный FAQ по Ruby" lang: ru header: |
- Content + Оглавление | 1 | - 2 + 2 | - 3 + 3 | - 4 + 4 | - 5 + 5 | - 6 + 6 | - 7 + 7 | - 8 + 8 | - 9 + 9 | - 10 + 10 | - 11 + 11
-

Official Ruby FAQ

+

Официальный FAQ по Ruby

--- {% include faq-notice.md %} -## General questions +## Общие вопросы -### What is Ruby? +### Что такое Ruby? -Ruby is a simple and powerful object-oriented programming language, created by -Yukihiro Matsumoto (who goes by the handle "Matz" in this document and on the -mailing lists). +Ruby — это простой и мощный объектно-ориентированный язык программирования, созданный +Yukihiro Matsumoto (который использует никнейм "Matz" в этом документе и в +списках рассылки). -Like Perl, Ruby is good at text processing. Like Smalltalk, everything in Ruby -is an object, and Ruby has blocks, iterators, meta-classes and other good -stuff. +Подобно Perl, Ruby хорош в обработке текста. Подобно Smalltalk, все в Ruby +является объектом, и в Ruby есть блоки, итераторы, метаклассы и другие хорошие +вещи. -You can use Ruby to write servers, experiment with prototypes, and for -everyday programming tasks. As a fully-integrated object-oriented language, -Ruby scales well. +Вы можете использовать Ruby для написания серверов, экспериментов с прототипами и для +повседневных задач программирования. Как полностью интегрированный объектно-ориентированный язык, +Ruby хорошо масштабируется. -Ruby features: +Возможности Ruby: -* Simple syntax, -* Basic OO features (classes, methods, objects, and so on), -* Special OO features (mixins, singleton methods, renaming, and so on), -* Operator overloading, -* Exception handling, -* Iterators and closures, -* Garbage collection, -* Dynamic loading (depending on the architecture), -* High transportability (runs on various Unices, Windows, DOS, macOS, OS/2, - Amiga, and so on). +* Простой синтаксис, +* Базовые возможности ООП (классы, методы, объекты и так далее), +* Специальные возможности ООП (примеси, синглтон-методы, переименование и так далее), +* Перегрузка операторов, +* Обработка исключений, +* Итераторы и замыкания, +* Сборка мусора, +* Динамическая загрузка (в зависимости от архитектуры), +* Высокая переносимость (работает на различных Unices, Windows, DOS, macOS, OS/2, + Amiga и так далее). -### Show me some Ruby code! +### Покажите мне немного кода на Ruby! -Let's define a class called `Person`, with a name and an age. We'll test our -code by creating a few people and examining them. +Давайте определим класс с названием `Person`, с именем и возрастом. Мы проверим наш +код, создав несколько человек и изучив их. ~~~ class Person @@ -90,8 +90,8 @@ p1 # => Elmo (4) p2 # => Zoe (7) ~~~ -Now let's populate an array of people by reading their names and ages from a -file `ages` containing lines like: +Теперь давайте заполним массив людей, считывая их имена и возраст из +файла `ages`, содержащего строки вида: ~~~ Bert: 8 @@ -101,9 +101,9 @@ Ernie: 8 Zoe: 7 ~~~ -The code uses regular expressions to parse successive lines from the input -file, creating a new `Person` object for each match and pushing it onto the -end of the array `people`. +Код использует регулярные выражения для парсинга последовательных строк из входного +файла, создавая новый объект `Person` для каждого совпадения и добавляя его в +конец массива `people`. ~~~ people = Array.new @@ -115,16 +115,16 @@ end people # => [Bert (8), Cookie (11), Elmo (4), Ernie (8), Zoe (7)] ~~~ -Now, let's sort the result based on the person's age. There are many ways to -do this. We can define a sort block, which tells Ruby how to do the comparison -of two people: +Теперь давайте отсортируем результат на основе возраста человека. Существует множество способов +сделать это. Мы можем определить блок сортировки, который указывает Ruby, как выполнять сравнение +двух людей: ~~~ sorted = people.sort {|a, b| a.age <=> b.age } sorted # => [Elmo (4), Zoe (7), Bert (8), Ernie (8), Cookie (11)] ~~~ -Another way would be to change the comparison method for class `Person`: +Другим способом было бы изменение метода сравнения для класса `Person`: ~~~ class Person @@ -135,161 +135,160 @@ end people.sort # => [Elmo (4), Zoe (7), Bert (8), Ernie (8), Cookie (11)] ~~~ -### Why the name “Ruby”? +### Почему название «Ruby»? -Influenced by Perl, Matz wanted to use a jewel name for his new language, so -he named Ruby after a colleague's birthstone. +Под влиянием Perl, Matz хотел использовать имя драгоценного камня для своего нового языка, поэтому +он назвал Ruby в честь камня рождения своего коллеги. -Later, he realized that Ruby comes right after Perl in several situations. -In birthstones, pearl is June, ruby is July. When measuring font sizes, -pearl is 5pt, ruby is 5.5pt. He thought Ruby was a good name for a -programming language newer (and hopefully better) than Perl. +Позже он понял, что Ruby (рубин) идет сразу после Perl (жемчуг) в нескольких ситуациях. +В камнях рождения жемчуг — это июнь, рубин — июль. При измерении размеров шрифта, +pearl составляет 5pt, ruby — 5.5pt. Он подумал, что Ruby — хорошее имя для +языка программирования, более нового (и, как мы надеемся, лучшего), чем Perl. -(Based on an explanation from Matz in [\[ruby-talk:00394\]][ruby-talk:00394] -on June 11, 1999.) +(Основано на объяснении от Matz в [\[ruby-talk:00394\]][ruby-talk:00394] +от 11 июня 1999 года.) [ruby-talk:00394]: https://blade.ruby-lang.org/ruby-talk/394 -### What is the history of Ruby? +### Какова история Ruby? -The following is a summary of a posting made by Matz in -[\[ruby-talk:00382\]][ruby-talk:00382] on June 4, 1999. -(The birthday of Ruby has been corrected in +Ниже приводится краткое изложение сообщения, сделанного от Matz в +[\[ruby-talk:00382\]][ruby-talk:00382] от 4 июня 1999 года. +(День рождения Ruby был исправлен в [\[ruby-list:15977\]][ruby-list:15977].) -> Well, Ruby was born on February 24, 1993. I was talking with my colleague -> about the possibility of an object-oriented scripting language. I knew Perl -> (Perl4, not Perl5), but I didn't like it really, because it had the smell of -> a toy language (it still has). The object-oriented scripting language seemed -> very promising. +> Что ж, Ruby родился 24 февраля 1993 года. Я разговаривал со своим коллегой +> о возможности создания объектно-ориентированного скриптового языка. Я знал Perl +> (Perl4, не Perl5), но он мне не очень нравился, потому что в нем чувствовался запах +> игрушечного языка (и до сих пор чувствуется). Объектно-ориентированный скриптовый язык казался +> очень многообещающим. -> I knew Python then. But I didn't like it, because I didn't think it was a -> true object-oriented language---OO features appeared to be an add-on to the -> language. As a language manic and OO fan for 15 years, I really wanted a -> genuine object-oriented, easy-to-use scripting language. I looked for, but -> couldn't find one. +> Я тогда знал Python. Но он мне не нравился, потому что я не считал его +> по-настоящему объектно-ориентированным языком — возможности ООП казались дополнением к +> языку. Как маньяк языков и фанат ООП с 15-летним стажем, я действительно хотел +> настоящий объектно-ориентированный, простой в использовании скриптовый язык. Я искал, но +> не смог такого найти. -> So, I decided to make it. It took several months to make the interpreter -> run. I put into it the features I love to have in my language, such as -> iterators, exception handling, garbage collection. +> Поэтому я решил создать его сам. Мне потребовалось несколько месяцев, чтобы заставить +> интерпретатор работать. Я добавил в него возможности, которые хотел бы видеть в своем языке, такие как +> итераторы, обработка исключений, сборка мусора. -> Then, I reorganized the features of Perl into a class library, and -> implemented them. I posted Ruby 0.95 to the Japanese domestic newsgroups -> in Dec. 1995. +> Затем я реорганизовал возможности Perl в библиотеку классов и +> реализовал их. Я опубликовал Ruby 0.95 в японских внутренних новостных группах +> в декабре 1995 года. -> Since then, highly active mailing lists have been established and -> web pages formed. +> С тех пор были созданы очень активные списки рассылки и +> сформированы веб-страницы. [ruby-talk:00382]: https://blade.ruby-lang.org/ruby-talk/382 [ruby-list:15977]: https://blade.ruby-lang.org/ruby-list/15977 -### Where is the Ruby Home Page? +### Где находится домашняя страница Ruby? -The official Ruby Home Page is [www.ruby-lang.org](https://www.ruby-lang.org). -Besides the English and Japanese versions, there exist translations -into various other languages. +Официальная домашняя страница Ruby — [www.ruby-lang.org](https://www.ruby-lang.org). +Помимо английской и японской версий, существуют переводы +на различные другие языки. -Good starting points for finding Ruby information are the -[Documentation](/en/documentation/) and [Community](/en/community/) -pages. +Хорошими отправными точками для поиска информации о Ruby являются страницы +[Документация](/ru/documentation/) и [Сообщество](/ru/community/). -### Is there a Ruby newsgroup? +### Есть ли новостная группа по Ruby? -comp.lang.ruby was established in May, 2000 (thanks to the efforts of +comp.lang.ruby была создана в мае 2000 года (спасибо усилиям [Conrad Schneiker](mailto:schneiker@jump.net)). -### Is there a Ruby mailing list? +### Есть ли список рассылки по Ruby? -There are several mailing lists talking about Ruby. See the -[Mailing Lists](/en/community/mailing-lists/) -page for more information. +Существует несколько списков рассылки, обсуждающих Ruby. Смотрите страницу +[Списки рассылки](/ru/community/mailing-lists/) +для получения дополнительной информации. -You can search the mailing list archives using +Вы можете искать по архивам списка рассылки с помощью [https://ml.ruby-lang.org/archives/list/ruby-talk@ml.ruby-lang.org/](https://ml.ruby-lang.org/archives/list/ruby-talk@ml.ruby-lang.org/). -(This is the URL for the ruby-talk list, munge as required for the others). +(Это URL для списка ruby-talk, измените его по мере необходимости для других). -### How can I thread the mailing list in mutt? +### Как я могу структурировать список рассылки по цепочкам в mutt? {% include warnings/faq-out-of-date.html %} -For some of the Ruby mailing lists, the mailing list software adds a prefix -to the subject lines, for example `ruby-core:1234`. This can confuse the -threading in some mail user agents. +В некоторых списках рассылки по Ruby программное обеспечение списка добавляет префикс +к темам сообщений, например `ruby-core:1234`. Это может запутать +группировку по цепочкам (threading) в некоторых почтовых клиентах. -In mutt, you can get threading to work using the following variable setting. +В mutt вы можете заставить группировку работать, используя следующую настройку переменной. ~~~ # reply regexp, to support MLs like ruby-talk. set reply_regexp="^(\[[a-z0-9:-]+\][[:space:]]*)?(re([\[0-9\]+])*|aw):[[:space:]]*" ~~~ -### Which is correct, “Ruby” or “ruby”? +### Как правильно, «Ruby» или «ruby»? -Officially, the language is called “Ruby”. On most systems, it is invoked -using the command `ruby`. It's OK to use “ruby” instead of “Ruby”. +Официально язык называется «Ruby». На большинстве систем он вызывается +с помощью команды `ruby`. Допустимо использовать «ruby» вместо «Ruby». -Please don't use “RUBY” as the language name. +Пожалуйста, не используйте «RUBY» в качестве названия языка. -Originally, or historically, it was called “ruby”. +Изначально, или исторически, он назывался «ruby». -### Are there any Ruby books? +### Есть ли книги по Ruby? {% include warnings/faq-out-of-date.html %} * Programming Ruby: The Pragmatic Programmer's Guide, - (the Pickaxe Book) by David Thomas and Andrew Hunt: ISBN 0-20171-089-7, - Addison-Wesley, October 2000. + (книга с киркой) от David Thomas и Andrew Hunt: ISBN 0-20171-089-7, + Addison-Wesley, октябрь 2000. -* A Japanese language Ruby reference book by Matz et al. and published by - ASCII is available in Japan (ISBN 4-7561-3254-5). An English translation, - “The Ruby Programming Language”, is available from O'Reilly & Associates +* Справочник по Ruby на японском языке от Matz и других, изданный + ASCII, доступен в Японии (ISBN 4-7561-3254-5). Английский перевод, + «The Ruby Programming Language», доступен от O'Reilly & Associates (ISBN 978-0596516178). -* A Japanese language “Ruby Pocket Reference” is published by O'Reilly Japan - (ISBN 4-87311-023-8). Let O'Reilly in the US know if you'd like to see a - translation. +* «Ruby Pocket Reference» на японском языке издан O'Reilly Japan + (ISBN 4-87311-023-8). Сообщите O'Reilly в США, если хотите увидеть + перевод. -* In addition, “Mastering Regular Expressions”, by Jeffrey Friedl, - (the Hip Owl Book): ISBN 1-56592-257-3 from O'Reilly & Associates, - is a reference work that covers the art and implementation of regular - expressions in various programming languages. Most of it is highly - relevant to Ruby regular expressions. +* Кроме того, «Mastering Regular Expressions» от Jeffrey Friedl, + (книга с совой): ISBN 1-56592-257-3 от O'Reilly & Associates, + — это справочник, который охватывает искусство и реализацию регулярных + выражений в различных языках программирования. Большая часть из этого крайне + актуальна для регулярных выражений в Ruby. -### Which editors provide support for Ruby? +### Какие редакторы поддерживают Ruby? {% include warnings/faq-out-of-date.html %} * [Emacs](http://www.gnu.org/software/emacs/emacs.html) - or [XEmacs](http://www.xemacs.org/): `ruby-mode.el` is supplied in the Ruby - distribution. With some versions of XEmacs, you may need to add - `(load "font-lock")` to your `.emacs` file to allow `ruby-mode.el` to detect - the syntax highlighting package you are using. -* [Vim](http://www.vim.org/): Vim 5.7 and later have Ruby syntax files as - standard in the runtime package. For prior versions, a syntax file for Ruby - is available at + или [XEmacs](http://www.xemacs.org/): `ruby-mode.el` поставляется в дистрибутиве + Ruby. В некоторых версиях XEmacs вам может потребоваться добавить + `(load "font-lock")` в ваш файл `.emacs`, чтобы позволить `ruby-mode.el` обнаружить + пакет подсветки синтаксиса, который вы используете. +* [Vim](http://www.vim.org/): Vim 5.7 и более поздние версии имеют файлы синтаксиса Ruby в качестве + стандарта в пакете среды выполнения. Для предыдущих версий файл синтаксиса для Ruby + доступен на [http://www.xs4all.nl/~hipster/lib/ruby/ruby.vim](http://www.xs4all.nl/~hipster/lib/ruby/ruby.vim). -* [Jedit](http://jedit.sourceforge.net/): A portable editor written in Java, - comes with support for Ruby. -* Barry Shultz has written a Ruby definition file for TextPad, available at +* [Jedit](http://jedit.sourceforge.net/): Портативный редактор, написанный на Java, + поставляется с поддержкой Ruby. +* Barry Shultz написал файл определений Ruby для TextPad, доступный на [https://www.textpad.com/add-ons/synn2t.html](https://www.textpad.com/add-ons/synn2t.html). -### How can I annotate Ruby code with its results? +### Как я могу аннотировать код на Ruby его результатами? {% include warnings/faq-out-of-date.html %} -People commonly annotate Ruby code by showing the results of executing each -statement as a comment attached to that statement. For example, in the -following code, we show that the assignment generates the string "Billy Bob", -and then the result of extracting some substrings. +Люди часто аннотируют код на Ruby, показывая результаты выполнения каждого +выражения в виде комментария, прикрепленного к этому выражению. Например, в +следующем коде мы показываем, что присваивание генерирует строку "Billy Bob", +а затем результат извлечения некоторых подстрок. ~~~ str = "Billy" + " Bob" # => "Billy Bob" str[0,1] + str[2,1] + str[-2,2] # => "Blob" ~~~ -Emacs and vim users can integrate this with their editing environments, which -is useful if you want to send people e-mail with annotated Ruby code. Having -installed `xmp`, Emacs users can add the following to their `.emacs` file: +Пользователи Emacs и vim могут интегрировать это в свои среды редактирования, что +полезно, если вы хотите отправлять людям электронные письма с аннотированным кодом на Ruby. Установив +`xmp`, пользователи Emacs могут добавить следующее в свой файл `.emacs`: ~~~ (defun ruby-xmp-region (reg-start reg-end) @@ -302,36 +301,35 @@ installed `xmp`, Emacs users can add the following to their `.emacs` file: (global-set-key [(meta f10)] 'ruby-xmp-region) ~~~ -Vim users can use the mapping (thanks to hipster): +Пользователи Vim могут использовать маппинг (спасибо hipster): ~~~ map :!ruby -r xmp -n -e 'xmp($_, "\%l\t\t\# \%r\n")' ~~~ -In both cases, highlight a region of code and hit Meta-F10 to annotate it. +В обоих случаях выделите область кода и нажмите Meta-F10 для ее аннотирования. -### I can't understand Ruby even after reading the manual! +### Я не могу понять Ruby даже после прочтения руководства! {% include warnings/faq-out-of-date.html %} -The syntax of Ruby has been fairly stable since Ruby 1.0, but new features are -added every now and then. So, the books and the online documentation can get -behind. +Синтаксис Ruby был довольно стабильным начиная с Ruby 1.0, но время от времени +добавляются новые возможности. Поэтому книги и онлайн-документация могут устаревать. -If you have a problem, feel free to ask in the mailing list -(see the [Mailing Lists page](/en/community/mailing-lists/)). -Generally you'll get timely answers from Matz himself, the -author of the language, from other gurus, and from those who have solved -problems similar to your own. +Если у вас возникла проблема, не стесняйтесь задавать вопросы в списке рассылки +(смотрите страницу [Списки рассылки](/ru/community/mailing-lists/)). +Обычно вы получите своевременные ответы от Matz, автора языка, +от других гуру и от тех, кто уже решил +проблемы, похожие на вашу. -Please include the output of `ruby -v` along with any problematic -source code. +Пожалуйста, включайте вывод `ruby -v` вместе с любым проблемным +исходным кодом. -If you have a problem using [`irb`](../10/#irb), -be aware that it has some limitations. -Try the script using `irb --single-irb`, or directly using the -`ruby` command. +Если у вас возникла проблема с использованием [`irb`](../10/#irb), +имейте в виду, что у него есть некоторые ограничения. +Попробуйте запустить скрипт с помощью `irb --single-irb`, или напрямую используя +команду `ruby`. -There might be similar questions in the mailing list, and it is good -netiquette to read through recent mails (RFC1855:3.1.1, 3.1.2) before asking. -But do ask on the list, and a correct answer will be forthcoming. +В списке рассылки могут быть похожие вопросы, и хорошим +сетевым этикетом является чтение недавних писем (RFC1855:3.1.1, 3.1.2) перед тем, как задать вопрос. +Но обязательно спрашивайте в списке, и правильный ответ не заставит себя ждать. diff --git a/ru/documentation/faq/10/index.md b/ru/documentation/faq/10/index.md index 866ccc0714..6e3524acad 100644 --- a/ru/documentation/faq/10/index.md +++ b/ru/documentation/faq/10/index.md @@ -1,69 +1,60 @@ --- layout: page -title: "Official Ruby FAQ" +title: "Официальный FAQ по Ruby" lang: ru header: |
- Content + Оглавление | - 1 + 1 | - 2 + 2 | - 3 + 3 | - 4 + 4 | - 5 + 5 | - 6 + 6 | - 7 + 7 | - 8 + 8 | - 9 + 9 | 10 | - 11 + 11
-

Official Ruby FAQ

+

Официальный FAQ по Ruby

--- {% include faq-notice.md %} -## Extension library +## Библиотека расширений -### How can I use Ruby interactively? +### Как я могу использовать Ruby интерактивно? {: #irb} {% include warnings/faq-out-of-date.html %} -You can try using `irb`. The following is paraphrased from Kentaro Goto -(Gotoken), and originally appeared in [\[ruby-talk:444\]][ruby-talk:444]. - -1. Get the latest tarball of `irb` from the - [contrib directory](ftp://ftp.netlab.co.jp/pub/lang/ruby/contrib/) - in the Ruby archive. -2. Extract the `irb` directory tree. -3. Add the location of the `irb/` directory to the `$RUBYLIB` - environment variable. -4. Make a symbolic link from `$RUBYLIB/irb/irb.rb` to a file called `irb` - somewhere in your path. +Вы можете попробовать использовать `irb`. Ниже приведено переложение текста Kentaro Goto (Gotoken), который изначально появился в [\[ruby-talk:444\]][ruby-talk:444]. + +1. Получите последний тарбол `irb` из [директории contrib](ftp://ftp.netlab.co.jp/pub/lang/ruby/contrib/) в архиве Ruby. +2. Распакуйте дерево директорий `irb`. +3. Добавьте путь к директории `irb/` в переменную окружения `$RUBYLIB`. +4. Создайте символическую ссылку из `$RUBYLIB/irb/irb.rb` на файл с именем `irb` где-нибудь в вашем пути PATH. 5. `chmod +x $RUBYLIB/irb/irb.rb` -6. Possibly use `rehash` to tell your login shell about the new command. -7. Type `irb`. +6. Возможно, используйте `rehash`, чтобы сообщить вашей оболочке о новой команде. +7. Введите `irb`. -If the readline extension module works with your interpreter, it makes `irb` -a lot more fun to use. +Если модуль расширения readline работает с вашим интерпретатором, это сделает использование `irb` гораздо приятнее. -There is also a simple program, `eval`, in the `samples/` directory of the -Ruby distribution. It lets you enter expressions and view their values. -You can copy `eval` into the `site_ruby` directory in the Ruby tree, and -then invoke it using: +В директории `samples/` дистрибутива Ruby также есть простая программа `eval`. Она позволяет вводить выражения и просматривать их значения. Вы можете скопировать `eval` в директорию `site_ruby` в дереве Ruby, а затем вызывать её с помощью: ~~~ ruby -r eval -e0 @@ -71,75 +62,54 @@ ruby -r eval -e0 [ruby-talk:444]: https://blade.ruby-lang.org/ruby-talk/444 -### Is there a debugger for Ruby? +### Есть ли отладчик для Ruby? -There is a gdb-like debugger for Ruby. +Для Ruby существует gdb-подобный отладчик. ~~~ ruby -r debug your_program ~~~ -### How can I use a library written in C from Ruby? +### Как я могу использовать библиотеку, написанную на C, из Ruby? -Of all the scripting languages, Ruby is probably the easiest to extend. -There are no problems with reference counting and variable types, and very -few interfaces to learn. In fact, C code used to extend Ruby often ends up -looking surprisingly like Ruby code itself. +Из всех скриптовых языков Ruby, вероятно, проще всего расширять. Здесь нет проблем с подсчетом ссылок и типами переменных, и нужно изучить совсем немного интерфейсов. На самом деле код на C, используемый для расширения Ruby, часто в итоге выглядит удивительно похожим на сам код Ruby. -First, read the `doc/extension.rdoc` file in the Ruby source, -or read [extension.rdoc on docs.ruby-lang.org][extension-rdoc]. -This is a good document, not only if you are writing an extension library, -but also if you want to understand Ruby more deeply. +Сначала прочитайте файл `doc/extension.rdoc` в исходниках Ruby или прочитайте [extension.rdoc на docs.ruby-lang.org][extension-rdoc]. Это отличный документ не только если вы пишете библиотеку расширения, но и если вы хотите глубже понять Ruby. -Then, the RubyGems site provides a -[guide on creating gems with extensions][rubygems-guide]. -It shows how to setup a gem with C extensions that are built at install time. -It has also links to some existing gems that wrap C libraries and -to further reading. +Затем сайт RubyGems предоставляет [руководство по созданию гемов с расширениями][rubygems-guide]. В нем показано, как настроить гем с расширениями на C, которые собираются во время установки. Там также есть ссылки на некоторые существующие гемы, которые оборачивают библиотеки на C, и материалы для дальнейшего чтения. -You might also want to have a look at the source of the interpreter itself, -and at the various supplied extensions in the `ext/` directory -(you can browse the [Ruby repository on GitHub][ruby-github]). +Вы также можете взглянуть на исходный код самого интерпретатора и на различные поставляемые расширения в директории `ext/` (вы можете просмотреть [репозиторий Ruby на GitHub][ruby-github]). [extension-rdoc]: https://docs.ruby-lang.org/en/master/extension_rdoc.html [rubygems-guide]: http://guides.rubygems.org/gems-with-extensions/ [ruby-github]: https://github.com/ruby/ruby -### Can I use Tcl/Tk in Ruby? +### Могу ли я использовать Tcl/Tk в Ruby? {% include warnings/faq-out-of-date.html %} -There are two interfaces to Tcl/Tk included in the standard distribution. -One is under `ext/tcltk/` and loaded with `require "tcltk"`. The syntax is -very close to that Tcl which is passed on to the Tcl interpreter. -Unfortunately, the description for this library is written in Japanese. +В стандартный дистрибутив включены два интерфейса к Tcl/Tk. Один находится в `ext/tcltk/` и загружается с помощью `require "tcltk"`. Синтаксис очень близок к синтаксису Tcl, который передается интерпретатору Tcl. К сожалению, описание этой библиотеки написано на японском языке. -The other is under `ext/tk/` and loaded with `require "tk"`. Its syntax -is closer to the style of the Tk interface provided by the Perl and Python -interfaces. +Другой находится в `ext/tk/` и загружается с помощью `require "tk"`. Его синтаксис ближе к стилю интерфейса Tk, предоставляемого интерфейсами Perl и Python. -### Tk won't work. Why? +### Tk не работает. Почему? {% include warnings/faq-out-of-date.html %} -Your Tk version may be old, try a newer version. +Ваша версия Tk может быть старой, попробуйте более новую версию. -### Can I use gtk+ or xforms interfaces in Ruby? +### Могу ли я использовать интерфейсы gtk+ или xforms в Ruby? {% include warnings/faq-out-of-date.html %} -You will find `ruby-gtk-x.xx.tar.gz` and `ruby-forms-x.x.tar.gz` -under `contrib/` on the Ruby ftp sites. +Вы найдете `ruby-gtk-x.xx.tar.gz` и `ruby-forms-x.x.tar.gz` в директории `contrib/` на ftp-сайтах Ruby. -### How can I do date arithmetic? +### Как я могу выполнять арифметические операции с датами? {% include warnings/faq-out-of-date.html %} -A `Time` object can express only the dates between Jan 1, 1970 and -Jan 19, 2038. +Объект `Time` может выражать только даты между 1 января 1970 года и 19 января 2038 года. -Two standard extension library modules are provided: -`require "date"`, which is simple and uses the English calendar, -and `require "date2"`, which is more general purpose. +Предоставляются два стандартных модуля библиотеки расширений: `require "date"`, который прост и использует английский календарь, и `require "date2"`, который более универсален. -Also see `sample/cal.rb`. +Также смотрите `sample/cal.rb`. diff --git a/ru/documentation/faq/11/index.md b/ru/documentation/faq/11/index.md index 499904c325..aeb2aa3ada 100644 --- a/ru/documentation/faq/11/index.md +++ b/ru/documentation/faq/11/index.md @@ -1,69 +1,63 @@ --- layout: page -title: "Official Ruby FAQ" +title: "Официальный FAQ по Ruby" lang: ru header: |
- Content + Оглавление | - 1 + 1 | - 2 + 2 | - 3 + 3 | - 4 + 4 | - 5 + 5 | - 6 + 6 | - 7 + 7 | - 8 + 8 | - 9 + 9 | - 10 + 10 | 11
-

Official Ruby FAQ

+

Официальный FAQ по Ruby

--- {% include faq-notice.md %} -## Other features +## Другие возможности -### What does `a ? b : c` mean? +### Что означает `a ? b : c`? -This is the so-called “ternary operator” and is the same as saying -`if a then b else c end`. +Это так называемый «тернарный оператор», и он эквивалентен записи `if a then b else c end`. -### How can I count the number of lines in a file? +### Как я могу подсчитать количество строк в файле? -The following code may give the fastest result. +Следующий код может дать самый быстрый результат. ~~~ File.readlines("example").size # => 3 ~~~ -### What do `MatchData#begin` and `MatchData#end` return? +### Что возвращают `MatchData#begin` и `MatchData#end`? -They act with `$~`, and return the start index and the end index of -the matched data in the original string. See an example in -[tab expansion](../9/#tab-expansion). +Они работают с `$~` и возвращают начальный и конечный индексы совпавших данных в исходной строке. Смотрите пример в разделе [развертывание табуляции](../9/#tab-expansion). -### How can I sum the elements in an array? +### Как я могу просуммировать элементы массива? {% include warnings/faq-out-of-date.html %} -Rather than solve the specific problem, let's solve the general case. -The first thing we will do is produce a method that will iterate over -an `Enumerable` object and collect a single result. Smalltalk calls that -method inject, so we will too: +Вместо решения конкретной задачи, давайте решим её в общем виде. Первое, что мы сделаем — создадим метод, который будет итерироваться по объекту `Enumerable` и собирать единый результат. В Smalltalk этот метод называется inject, так же назовем его и мы: ~~~ module Enumerable @@ -77,12 +71,7 @@ module Enumerable end ~~~ -Notice how we have added the method to `Enumerable`. This means that anything -that includes Enumerable can now use `inject`. But how do we use it? It takes -a single argument `n` and a block. For each element in the thing being -enumerated, it calls the block, passing in `n` and the element itself. -The result of the block is assigned back to `n`. So, to define `sum`, -we could write: +Обратите внимание, как мы добавили метод в `Enumerable`. Это означает, что все, что включает в себя Enumerable, теперь может использовать `inject`. Но как нам его использовать? Он принимает один аргумент `n` и блок. Для каждого перечисляемого элемента он вызывает блок, передавая `n` и сам элемент. Результат выполнения блока присваивается обратно в `n`. Таким образом, чтобы определить `sum`, мы могли бы написать: ~~~ module Enumerable @@ -95,17 +84,13 @@ end (1..100).sum # => 5050 ~~~ -### How can I use continuations? +### Как я могу использовать продолжения (continuations)? {% include warnings/faq-out-of-date.html %} -Ruby's continuations allow you to create an object representing a place in a -Ruby program, and then return to that place at any time (even if it has -apparently gone out of scope). Continuations can be used to implement complex -control structures, but are typically more useful as ways of confusing people. +Продолжения (continuations) в Ruby позволяют создать объект, представляющий определенное место в программе на Ruby, а затем вернуться в это место в любое время (даже если оно, казалось бы, вышло за пределы области видимости). Продолжения можно использовать для реализации сложных структур управления, но обычно они более полезны как способ запутать людей. -In [\[ruby-talk:4482\]][ruby-talk:4482], Jim Weirich posted the following -examples of continuations: +В [\[ruby-talk:4482\]][ruby-talk:4482], Jim Weirich опубликовал следующие примеры использования продолжений: ~~~ # -------------------------------------------------------------------- diff --git a/ru/documentation/faq/2/index.md b/ru/documentation/faq/2/index.md index e26d6d09cd..fd105277b5 100644 --- a/ru/documentation/faq/2/index.md +++ b/ru/documentation/faq/2/index.md @@ -1,102 +1,102 @@ --- layout: page -title: "Official Ruby FAQ" +title: "Официальный FAQ по Ruby" lang: ru header: |
- Content + Оглавление | - 1 + 1 | 2 | - 3 + 3 | - 4 + 4 | - 5 + 5 | - 6 + 6 | - 7 + 7 | - 8 + 8 | - 9 + 9 | - 10 + 10 | - 11 + 11
-

Official Ruby FAQ

+

Официальный FAQ по Ruby

--- {% include faq-notice.md %} -## How does Ruby stack up against...? +## Как Ruby выглядит на фоне...? -### How does Ruby compare with Python? +### Как Ruby соотносится с Python? -Python and Ruby are both object oriented languages that provide a smooth -transition from procedural to OO programming styles. Smalltalk, by contrast, -is object only---you can't do anything until you understand objects, -inheritance and the sizable Smalltalk class hierarchy. By providing procedural -training wheels, Python and Ruby “fix” one of the features that may have -kept Smalltalk out of the mainstream. The two languages differ by approaching -this solution from opposite directions. +Python и Ruby — это оба объектно-ориентированные языки, которые обеспечивают плавный +переход от процедурного к объектно-ориентированному стилю программирования. Smalltalk, для контраста, +является исключительно объектным — вы ничего не можете сделать, пока не поймете объекты, +наследование и солидную иерархию классов Smalltalk. Предоставляя процедурные +вспомогательные средства, Python и Ruby «исправляют» одну из особенностей, которая, возможно, +удерживала Smalltalk в стороне от мейнстрима. Эти два языка отличаются тем, что подходят +к этому решению с противоположных сторон. -Python is a hybrid language. It has functions for procedural programming and -objects for OO programming. Python bridges the two worlds by allowing -functions and methods to interconvert using the explicit `self` parameter -of every method def. When a function is inserted into an object, the first -argument automagically becomes a reference to the receiver. +Python — гибридный язык. У него есть функции для процедурного программирования и +объекты для ООП. Python связывает эти два мира, позволяя +функциям и методам взаимопревращаться с использованием явного параметра `self` +каждого определения метода. Когда функция вставляется в объект, первый +аргумент автоматически становится ссылкой на получателя. -Ruby is a pure OO language that can masquerade as a procedural one. It has no -functions, only method calls. In a Ruby method the receiver, also called -`self`, is a hidden argument like `this` in C++. A `def` statement outside of -a class definition, which defines a function in Python, actually defines a method -in Ruby. These ersatz functions become private methods of class Object, the -root of the Ruby class hierarchy. Procedural programming is neatly solved from -the other direction---everything is an object. If the user doesn't grok -objects yet, they can just pretend that `def` is a function definition and -still get useful work done. +Ruby — это чисто объектно-ориентированный язык, который может маскироваться под процедурный. В нем нет +функций, только вызовы методов. В методе Ruby получатель, также называемый +`self`, является скрытым аргументом, подобно `this` в C++. Инструкция `def` вне +определения класса, которая в Python определяет функцию, в Ruby на самом деле определяет метод. +Эти эрзац-функции становятся приватными методами класса Object, +корня иерахии классов Ruby. Процедурное программирование изящно решается +с другой стороны — все является объектом. Если пользователь еще не осознает +объекты, он может просто притвориться, что `def` — это определение функции, и +все равно делать полезную работу. -Ruby's OO purity provides a number of features that Python lacks or is still -working toward: a unified type/class hierarchy, metaclasses, the ability to -subclass everything, and uniform method invocation (none of this `len()` is a -function but `items()` is a method rubbish). Ruby, like Smalltalk, only -supports single inheritance, but it does have a very powerful mixin concept: -a class definition may include a module, which inserts that module's methods, -constants, etc. into the class. +Чистота ООП в Ruby предоставляет ряд возможностей, которых не хватает Python или к которым он все еще +стремится: единая иерархия типов/классов, метаклассы, возможность +наследовать все, и единообразный вызов методов (ничего из этой чепухи, что `len()` — это +функция, а `items()` — это метод). Ruby, как и Smalltalk, поддерживает только +одиночное наследование, но в нем есть очень мощная концепция примесей (mixin): +определение класса может включать модуль, который вставляет методы этого модуля, +константы и т.д. в класс. -Ruby, again like Smalltalk, provides closures and code blocks and uses them -to the same good effect. The Ruby collection classes and iterators are -outstanding, much more powerful and elegant than the ad hoc solutions that -Python is sprouting (lambdas and list comprehensions). +Ruby, опять же как и Smalltalk, предоставляет замыкания и блоки кода и использует их +с тем же хорошим эффектом. Коллекции классов и итераторы Ruby +выдающиеся, гораздо более мощные и элегантные, чем специальные решения, которые +появляются в Python (лямбды и генераторы списков). -Ruby's syntax and design philosophy are heavily influenced by Perl. It has a -lot of syntactic variability. Statement modifiers (`if`, `unless`, `while`, -`until`, etc.) may appear at the end of any statement. Some key words are -optional (the `then` in an `if` statement for example). Parentheses may -sometimes be elided in method calls. The receiver of a method may usually be -elided. -Many, many things are lifted directly from Perl. -Built in regular expressions, `$_` and friends, here documents, the -single-quoted / double-quoted string distinction, `$` and `@` prefixes to -distinguish different kinds of names and so forth. +Синтаксис и философия дизайна Ruby находятся под сильным влиянием Perl. Он обладает +большой синтаксической вариативностью. Модификаторы инструкций (`if`, `unless`, `while`, +`until` и т.д.) могут появляться в конце любой инструкции. Некоторые ключевые слова +необязательны (например, `then` в инструкции `if`). Скобки +иногда можно опускать при вызовах методов. Получатель метода обычно также может быть +опущен. +Многое, многое заимствовано напрямую из Perl. +Встроенные регулярные выражения, `$_` и компания, heredoc, +различие между строками в одинарных и двойных кавычках, префиксы `$` и `@` +для различения разных видов имен и так далее. -If you like Perl, you will like Ruby and be right at home with its syntax. -If you like Smalltalk, you will like Ruby and be right at home with its -semantics. If you like Python, you may or may not be put off by the huge -difference in design philosophy between Python and Ruby/Perl. +Если вам нравится Perl, вам понравится Ruby и вы будете чувствовать себя как дома с его синтаксисом. +Если вам нравится Smalltalk, вам понравится Ruby и вы будете чувствовать себя как дома с его +семантикой. Если вам нравится Python, вас может оттолкнуть (или нет) огромная +разница в философии дизайна между Python и Ruby/Perl. -Ruby is much more complex than Python but its features, for the most part, -hang together well. Ruby is well designed and full of neat ideas that might be -mined for P3K. I'm not sure how many Python programmers will be attracted to -it though---it hasn't won me over (yet). But it is worthy of serious study and -could be a real threat to Perl. +Ruby намного сложнее Python, но его возможности, по большей части, +хорошо сочетаются друг с другом. Ruby хорошо спроектирован и полон отличных идей, которые можно было бы +использовать для P3K. Однако я не уверен, сколько программистов на Python он +привлечет — он меня (пока) не покорил. Но он достоин серьезного изучения и +мог бы стать реальной угрозой для Perl. -Posted by [John Dell'Aquila](mailto:jbd@alum.mit.edu) in comp.lang.python, -11/17/2000. Reproduced with permission. +Опубликовано от [John Dell'Aquila](mailto:jbd@alum.mit.edu) в comp.lang.python, +11/17/2000. Воспроизведено с разрешения. diff --git a/ru/documentation/faq/3/index.md b/ru/documentation/faq/3/index.md index 2e6405239d..864d2a7b57 100644 --- a/ru/documentation/faq/3/index.md +++ b/ru/documentation/faq/3/index.md @@ -1,67 +1,67 @@ --- layout: page -title: "Official Ruby FAQ" +title: "Официальный FAQ по Ruby" lang: ru header: |
- Content + Оглавление | - 1 + 1 | - 2 + 2 | 3 | - 4 + 4 | - 5 + 5 | - 6 + 6 | - 7 + 7 | - 8 + 8 | - 9 + 9 | - 10 + 10 | - 11 + 11
-

Official Ruby FAQ

+

Официальный FAQ по Ruby

--- {% include faq-notice.md %} -## Installing Ruby +## Установка Ruby -For current information on downloading and installing Ruby -see the [Installation](/en/documentation/installation/) -or [Downloads](/en/downloads/) page. +Актуальную информацию о скачивании и установке Ruby +смотрите на страницах [Установка](/ru/documentation/installation/) +или [Скачать](/ru/downloads/). -### What operating systems support Ruby? +### Какие операционные системы поддерживают Ruby? {% include warnings/faq-out-of-date.html %} -Ruby is developed under Linux, and is written in fairly straightforward C. -It runs under Linux and other UNIX-like operating systems, macOS, -Windows, DOS, BeOS, Amiga, Acorn Risc OS, and OS/2. +Ruby разрабатывается под Linux и написан на довольно простом C. +Он работает под Linux и другими UNIX-подобными операционными системами, macOS, +Windows, DOS, BeOS, Amiga, Acorn Risc OS и OS/2. -### Where can I get Ruby sources? +### Где я могу получить исходный код Ruby? -The latest version of Ruby can be downloaded from: -[www.ruby-lang.org/en/downloads/](/en/downloads/). -Mirror sites are also listed on this page. +Последнюю версию Ruby можно скачать с: +[www.ruby-lang.org/ru/downloads/](/ru/downloads/). +Зеркала также перечислены на этой странице. -Also on this page is a link to a nightly snapshot of the development tree. +Также на этой странице есть ссылка на ночной снапшот дерева разработки. -### Can I get to the development source tree? +### Могу ли я получить доступ к дереву исходного кода разработки? {% include warnings/faq-out-of-date.html %} -If you have a CVS client, you can check out the current source tree using: +Если у вас есть клиент CVS, вы можете получить текущее дерево исходного кода, используя: ~~~ $ cvs -d :pserver:anonymous@cvs.netlab.co.jp:/home/cvs login @@ -70,15 +70,12 @@ CVS password: guest $ cvs -d :pserver:anonymous@cvs.netlab.co.jp:/home/cvs co ruby ~~~ -If you do not have CVS you can get a nightly snapshot of the development -source from +Если у вас нет CVS, вы можете получить ночной снапшот исходного кода разработки с [https://cache.ruby-lang.org/pub/ruby/snapshot.tar.gz](https://cache.ruby-lang.org/pub/ruby/snapshot.tar.gz). -### How do I compile Ruby? +### Как мне скомпилировать Ruby? -Under Unix, Ruby uses the `autoconf` system to configure the build -environment. You don't need the `autoconf` command on your box to build Ruby -from a distribution; just use the commands: +Под Unix Ruby использует систему `autoconf` для настройки среды сборки. Вам не нужна команда `autoconf` на вашей машине, чтобы собрать Ruby из дистрибутива; просто используйте команды: ~~~ $ ./configure [configure options] @@ -87,32 +84,28 @@ $ make test $ make install ~~~ -You may need superuser privileges to install Ruby if you don't override the -default installation location (`/usr/local`). You can get a full list of -`configure` options using: +Вам могут понадобиться права суперпользователя для установки Ruby, если вы не переопределите стандартный путь установки (`/usr/local`). Вы можете получить полный список опций `configure`, используя: ~~~ $ ./configure --help ~~~ -If you are working from the source repository, you may need to run -`autoconf` before running `configure`. +Если вы работаете из репозитория исходного кода, вам может потребоваться запустить +`autoconf` перед запуском `configure`. -### How do I tell Ruby where my libraries are? +### Как мне указать Ruby, где находятся мои библиотеки? {% include warnings/faq-out-of-date.html %} -On some systems, the build process may fail to find libraries used by -extension modules (for example the `dbm` libraries). +На некоторых системах процесс сборки может не найти библиотеки, используемые модулями расширения (например, библиотеки `dbm`). -You can tell Ruby where to find libraries using options to `configure`. -From [\[ruby-talk:5041\]][ruby-talk:5041]: +Вы можете указать Ruby, где искать библиотеки, используя опции `configure`. Из [\[ruby-talk:5041\]][ruby-talk:5041]: ~~~ $ ./configure --with-xxx-yyy=DIR ~~~ -where xxx is either +где xxx это либо ~~~ opt extra software path in general @@ -123,7 +116,7 @@ tk ...for Tk... tcl ...for Tcl... ~~~ -and yyy is either +и yyy это либо ~~~ dir specifies -I DIR/include -L DIR/lib @@ -131,68 +124,49 @@ include specifies -I DIR lib specifies -L DIR ~~~ -On HP-UX, there may be problems building with `gcc`. Try using the native -compiler instead. WATANABE Tetsuya recommends: +На HP-UX могут возникнуть проблемы при сборке с помощью `gcc`. Попробуйте использовать нативный компилятор. WATANABE Tetsuya рекомендует: ~~~ $ CC="cc -Ae" CFLAGS=-O ./configure --prefix=/opt/gnu ~~~ -There may also be problems with HP's native `sed`. -He recommends installing the GNU equivalent. +Также могут быть проблемы с нативным `sed` от HP. +Он рекомендует установить аналог от GNU. [ruby-talk:5041]: https://blade.ruby-lang.org/ruby-talk/5041 -### Are precompiled binaries available? +### Доступны ли скомпилированные бинарные файлы? -A single download that contains everything you need to run Ruby under various -Windows operating systems is available from [RubyInstaller](https://rubyinstaller.org/). +Единый файл для скачивания, содержащий все необходимое для запуска Ruby в различных операционных системах Windows, доступен на [RubyInstaller](https://rubyinstaller.org/). -[Reuben Thomas](mailto:Reuben.Thomas@cl.cam.ac.uk) writes: +[Reuben Thomas](mailto:Reuben.Thomas@cl.cam.ac.uk) пишет: -> You could mention that there's a port to Acorn RISC OS, currently of v1.4.3. -> I made the port, and have no plans to maintain it, but I did send the -> patches to matz, so newer versions may well compile too. +> Вы могли бы упомянуть, что существует порт для Acorn RISC OS, в данный момент версии 1.4.3. +> Я сделал этот порт и не планирую его поддерживать, но я отправил +> патчи Matz, так что более новые версии тоже могут скомпилироваться. -### What's all this “cygwin”, “mingw”, and “djgpp” stuff? +### Что это за штуки «cygwin», «mingw» и «djgpp»? {% include warnings/faq-out-of-date.html %} -Ruby is written to take advantage of the rich feature set of a Unix -environment. Unfortunately, Windows is missing some of the functions, and -implements others differently. As a result, some kind of mapping layer is -needed to run Ruby (and other Unix-based programs) under Windows. +Ruby написан так, чтобы использовать богатый набор возможностей среды Unix. К сожалению, в Windows отсутствуют некоторые функции, а другие реализованы иначе. В результате для запуска Ruby (и других программ на базе Unix) в Windows требуется своего рода промежуточный слой. -You may come across different versions of the Ruby executable that use -different wrapper mapping layers. +Вы можете столкнуться с различными версиями исполняемого файла Ruby, которые используют разные слои сопоставления оберток. -The rbdj version is a stand-alone version of the Windows binary of Ruby. -It uses the DJ Delorie tools -([http://www.delorie.com](http://www.delorie.com)). +Версия rbdj — это автономная версия Windows-бинарника Ruby. Она использует инструменты DJ Delorie ([http://www.delorie.com](http://www.delorie.com)). -The rbcw version is a Windows binary of Ruby that requires the cygwin library, -available at [http://www.cygwin.com](http://www.cygwin.com) or from the -Ruby download pages. Cygwin is both an emulation layer and a set of -utilities initially produced by Cygnus Solutions (now part of Redhat). -The cygwin version of Ruby probably has the fullest set of features under -Windows, so most programmers will want to use it. +Версия rbcw — это Windows-бинарник Ruby, которому требуется библиотека cygwin, доступная на [http://www.cygwin.com](http://www.cygwin.com) или на страницах скачивания Ruby. Cygwin — это одновременно и уровень эмуляции, и набор утилит, изначально созданных Cygnus Solutions (ныне часть Redhat). Версия Ruby для cygwin, вероятно, обладает наиболее полным набором функций под Windows, поэтому большинство программистов предпочтут использовать именно её. -To use the rbcw version, you will need to install the cygwin .dll separately. -Once you have installed cygwin on your computer, copy `cygwin1.dll` (which -is found in the `bin` subdirectory of the cygwin distribution) to your -`Windows\System32` folder (or somewhere else on your path). +Чтобы использовать версию rbcw, вам нужно будет установить cygwin .dll отдельно. Как только вы установите cygwin на свой компьютер, скопируйте `cygwin1.dll` (который находится в поддиректории `bin` дистрибутива cygwin) в папку `Windows\System32` (или в другое место в вашем пути PATH). -Thanks to Anders Schneiderman for the basis of this description. +Спасибо Anders Schneiderman за основу этого описания. -### Why doesn't Tk graphics work under Windows? +### Почему графика Tk не работает в Windows? {% include warnings/faq-out-of-date.html %} -Is Tk installed correctly on your Windows box? Go to -[https://wiki.tcl-lang.org/page/Binary+Distributions](https://wiki.tcl-lang.org/page/Binary+Distributions#85b8647b1ec80c2fa1698c3c7e76204a944a95db2487347c51773f26b9dad6ae) -to find a precompiled binary Tcl/Tk distribution for your box. +Правильно ли установлен Tk на вашей Windows-машине? Перейдите на [https://wiki.tcl-lang.org/page/Binary+Distributions](https://wiki.tcl-lang.org/page/Binary+Distributions#85b8647b1ec80c2fa1698c3c7e76204a944a95db2487347c51773f26b9dad6ae), чтобы найти скомпилированный бинарный дистрибутив Tcl/Tk для вашей системы. -Are the environment variables `TCL_LIBRARY` and `TK_LIBRARY` pointing to the -directories containing tcl and tk? +Указывают ли переменные окружения `TCL_LIBRARY` и `TK_LIBRARY` на директории, содержащие tcl и tk? -Is the tk library in your path? +Находится ли библиотека tk в вашем пути PATH? diff --git a/ru/documentation/faq/4/index.md b/ru/documentation/faq/4/index.md index 92324b4b37..c66a426de4 100644 --- a/ru/documentation/faq/4/index.md +++ b/ru/documentation/faq/4/index.md @@ -1,65 +1,54 @@ --- layout: page -title: "Official Ruby FAQ" +title: "Официальный FAQ по Ruby" lang: ru header: |
- Content + Оглавление | - 1 + 1 | - 2 + 2 | - 3 + 3 | 4 | - 5 + 5 | - 6 + 6 | - 7 + 7 | - 8 + 8 | - 9 + 9 | - 10 + 10 | - 11 + 11
-

Official Ruby FAQ

+

Официальный FAQ по Ruby

--- {% include faq-notice.md %} -## Variables, constants, and arguments +## Переменные, константы и аргументы -### Does assignment generate a new copy of an object? +### Создает ли присваивание новую копию объекта? {: #assignment} -All variables and constants reference (point at) some object. (With the -exception of uninitialized local variables, which reference nothing. -These raise a `NameError` exception if used). When you assign to a variable, -or initialize a constant, you set the object that the variable or constant -references. +Все переменные и константы ссылаются (указывают) на какой-либо объект. (За исключением неинициализированных локальных переменных, которые ни на что не ссылаются. Они вызывают исключение `NameError` при использовании). Когда вы присваиваете значение переменной или инициализируете константу, вы устанавливаете объект, на который ссылается эта переменная или константа. -Assignment on its own therefore never creates a new copy of an object. +Само по себе присваивание никогда не создает новую копию объекта. -There's a slightly deeper explanation in certain special cases. Instances of -`Fixnum`, `NilClass`, `TrueClass`, and `FalseClass` are contained directly in -variables or constants---there is no reference involved. A variable holding -the number `42` or the constant `true` actually holds the value, and not a -reference to it. Assignment therefore physically produces a copy of objects -of these types. We discuss this more in -[Immediate and Reference Objects](../6/#immediate). +В некоторых особых случаях есть чуть более глубокое объяснение. Экземпляры `Fixnum`, `NilClass`, `TrueClass` и `FalseClass` содержатся непосредственно в переменных или константах — здесь нет ссылок. Переменная, содержащая число `42`, или константа `true` фактически хранят значение, а не ссылку на него. Присваивание, таким образом, физически создает копию объектов этих типов. Мы обсудим это подробнее в разделе [Непосредственные и ссылочные объекты](../6/#immediate). -### What is the scope of a local variable? +### Какова область видимости локальной переменной? -A new scope for a local variable is introduced in (1) the toplevel (main), -(2) a class (or module) definition, or (3) a method definition. +Новая область видимости для локальной переменной вводится в (1) верхнем уровне (main), (2) определении класса (или модуля) или (3) определении метода. ~~~ var = 1 # (1) @@ -75,7 +64,7 @@ puts "at top level: var = #{var}" Demo.new.method ~~~ -Produces: +Результат: ~~~ in class: var = 2 @@ -83,14 +72,9 @@ at top level: var = 1 in method: var = 3 ~~~ -(Note that the class definition is executable code: the trace message it -contains is written as the class is defined). +(Обратите внимание, что определение класса — это исполняемый код: трассировочное сообщение, которое он содержит, записывается по мере определения класса). -A block (`{ ... }` or `do ... end`) almost introduces a new scope ;-) -Local variables created within a block are not accessible outside the block. -However, if a local variable within the block has the same name as an existing -local variable in the caller's scope, then no new local variable is created, -and you can subsequently access that variable outside the block. +Блок (`{ ... }` или `do ... end`) почти вводит новую область видимости ;-) Локальные переменные, созданные внутри блока, недоступны вне блока. Однако, если локальная переменная внутри блока имеет то же имя, что и существующая локальная переменная в области видимости вызывающей стороны, то новая локальная переменная не создается, и вы можете впоследствии обращаться к этой переменной вне блока. ~~~ a = 0 @@ -99,11 +83,10 @@ a = 0 b = i*i end a # => 6 -# b is not defined here +# b здесь не определена ~~~ -This becomes significant when you use threading---each thread receives its -own copy of the variables local to the thread's block: +Это становится важным при использовании многопоточности — каждый поток получает свою собственную копию переменных, локальных для блока потока: ~~~ threads = [] @@ -123,8 +106,7 @@ end threads.each {|t| t.join } ~~~ -Might produce (in case the scheduler switches threads as hinted -by `Thread.pass`; this depends on OS and processor): +Может вывести (в случае, если планировщик переключает потоки, как указано в `Thread.pass`; это зависит от ОС и процессора): ~~~ one: 0 @@ -135,20 +117,11 @@ one: 3 two: 3 ~~~ -`while`, `until`, and `for` are control structures, not blocks, so local -variables within them will be accessible in the enclosing environment. -`loop`, however, is a method and the associated block introduces a new scope. +`while`, `until` и `for` — это структуры управления, а не блоки, поэтому локальные переменные внутри них будут доступны во внешней среде. `loop`, однако, является методом, и связанный с ним блок вводит новую область видимости. -### When does a local variable become accessible? +### Когда локальная переменная становится доступной? -Actually, the question may be better asked as: “at what point does Ruby work -out that something is a variable?” The problem arises because the simple -expression `a` could be either a variable or a call to a method with no -parameters. To decide which is the case, Ruby looks for assignment statements. -If at some point in the source prior to the use of `a` it sees it being -assigned to, it decides to parse `a` as a variable, otherwise it treats it -as a method. As a somewhat pathological case of this, consider this code -fragment, originally submitted by Clemens Hintze: +На самом деле, вопрос лучше поставить так: «в какой момент Ruby понимает, что что-то является переменной?» Проблема возникает потому, что простое выражение `a` может быть либо переменной, либо вызовом метода без параметров. Чтобы решить, что это за случай, Ruby ищет инструкции присваивания. Если в какой-то момент в исходном коде до использования `a` он видит, что `a` присваивается значение, он решает парсить `a` как переменную, в противном случае он рассматривает её как метод. В качестве несколько патологического примера рассмотрите этот фрагмент кода, изначально представленный Clemens Hintze: ~~~ def a @@ -167,7 +140,7 @@ end end ~~~ -Produces: +Результат: ~~~ a = 1 @@ -175,41 +148,30 @@ method `a' called a = 99 ~~~ -During the parse, Ruby sees the use of `a` in the first `puts` statement -and, as it hasn't yet seen any assignment to `a`, assumes that it is a method -call. By the time it gets to the second `puts` statement, though, it has seen -an assignment, and so treats `a` as a variable. +Во время парсинга Ruby видит использование `a` в первой инструкции `puts` и, поскольку он еще не видел никакого присваивания `a`, предполагает, что это вызов метода. Однако к тому моменту, когда он добирается до второй инструкции `puts`, он уже видел присваивание и поэтому рассматривает `a` как переменную. -Note that the assignment does not have to be executed---Ruby just has to have -seen it. This program does not raise an error: +Обратите внимание, что присваивание не обязательно должно быть выполнено — Ruby просто должен его увидеть. Эта программа не вызывает ошибки: ~~~ a = 1 if false; a # => nil ~~~ -This issue with variables is not normally a problem. If you do bump into it, -try putting an assignment such as `a = nil` before the first access to the -variable. This has the additional benefit of speeding up the access time to -local variables that subsequently appear in loops. +Эта проблема с переменными обычно не является помехой. Если вы столкнетесь с ней, попробуйте добавить присваивание вида `a = nil` перед первым обращением к переменной. Это дает дополнительное преимущество в виде ускорения времени доступа к локальным переменным, которые впоследствии появляются в циклах. -### What is the scope of a constant? +### Какова область видимости константы? -A constant defined in a class or module definition can be accessed directly -within that class's or module's definition. +Константа, определенная в определении класса или модуля, может быть доступна напрямую внутри определения этого класса или модуля. -You can directly access the constants in outer classes and modules from -within nested classes and modules. +Вы можете напрямую обращаться к константам во внешних классах и модулях из вложенных классов и модулей. -You can also directly access constants in superclasses and included modules. +Вы также можете напрямую обращаться к константам в суперклассах и включенных модулях. -Apart from these cases, you can access class and module constants using -the `::` operator, `ModuleName::CONST1` or `ClassName::CONST2`. +Помимо этих случаев, вы можете обращаться к константам классов и модулей, используя оператор `::`, например `ModuleName::CONST1` или `ClassName::CONST2`. -### How are arguments passed? +### Как передаются аргументы? -The actual argument is assigned to the formal argument when the method is -invoked. -(See [assignment](#assignment) for more on the semantics of assignment.) +Фактический аргумент присваивается формальному аргументу при вызове метода. +(Смотрите [присваивание](#assignment) для более подробной информации о семантике присваивания.) ~~~ def add_one(number) @@ -221,8 +183,7 @@ add_one(a) # => 2 a # => 1 ~~~ -As you are passing object references, it is possible that a method may modify -the contents of a mutable object passed into it. +Поскольку вы передаете ссылки на объекты, возможно, что метод изменит содержимое переданного в него изменяемого объекта. ~~~ def downer(string) @@ -234,26 +195,19 @@ downer(a) # => "hello" a # => "hello" ~~~ -There is no equivalent of other language's pass-by-reference semantics. +В Ruby нет эквивалента семантике передачи по ссылке, как в других языках. -### Does assignment to a formal argument influence the actual argument? +### Влияет ли присваивание формальному аргументу на фактический аргумент? -A formal argument is a local variable. Within a method, assigning to a formal -argument simply changes the argument to reference another object. +Формальный аргумент является локальной переменной. Внутри метода присваивание формальному аргументу просто изменяет аргумент так, чтобы он ссылался на другой объект. -### What happens when I invoke a method via a formal argument? +### Что происходит, когда я вызываю метод через формальный аргумент? -All Ruby variables (including method arguments) act as references to objects. -You can invoke methods in these objects to get or change the object's state -and to make the object do something. You can do this with objects passed to -methods. You need to be careful when doing this, as these kinds of side -effects can make programs hard to follow. +Все переменные Ruby (включая аргументы методов) выступают в качестве ссылок на объекты. Вы можете вызывать методы в этих объектах, чтобы получить или изменить состояние объекта и заставить объект что-то сделать. Вы можете делать это с объектами, переданными в методы. Вам нужно быть осторожными при этом, так как побочные эффекты такого рода могут сделать программы трудными для понимания. -### What does `*` prepended to an argument mean? +### Что означает `*` перед аргументом? -When used as part of a formal parameter list, the asterisk allows arbitrary -numbers of arguments to be passed to a method by collecting them into an -array, and assigning that array to the starred parameter. +При использовании в списке формальных параметров звездочка позволяет передавать методу произвольное количество аргументов, собирая их в массив и присваивая этот массив параметру со звездочкой. ~~~ def foo(prefix, *all) @@ -265,7 +219,7 @@ end foo("val = ", 1, 2, 3) ~~~ -Produces: +Результат: ~~~ val = 1 @@ -273,23 +227,22 @@ val = 2 val = 3 ~~~ -When used in a method call, `*` expands an array, passing its individual -elements as arguments. +При использовании в вызове метода `*` разворачивает массив, передавая его отдельные элементы в качестве аргументов. ~~~ a = [1, 2, 3] foo(*a) ~~~ -You can prepend `*` to the last argument of +Вы можете добавить `*` перед последним аргументом в следующих случаях: -1. Left hand side of a multiple assignment. -2. Right hand side of a multiple assignment. -3. Definition of method formal arguments. -4. Actual arguments in a method call. -5. In `when` clause of `case` structure. +1. Левая часть множественного присваивания. +2. Правая часть множественного присваивания. +3. Определение формальных аргументов метода. +4. Фактические аргументы в вызове метода. +5. В условии `when` структуры `case`. -For example: +Например: ~~~ x, *y = [7, 8, 9] @@ -301,15 +254,11 @@ x = [7, 8, 9] x # => [7, 8, 9] ~~~ -### What does `&` prepended to an argument mean? +### Что означает `&` перед аргументом? -If the last formal argument of a method is preceded with an ampersand (`&`), -a block following the method call will be converted into a `Proc` object -and assigned to the formal parameter. +Если перед последним формальным аргументом метода стоит амперсанд (`&`), блок, следующий за вызовом метода, будет преобразован в объект `Proc` и присвоен формальному параметру. -If the last actual argument in a method invocation is a `Proc` object, -you can precede its name with an ampersand to convert it into a block. -The method may then use `yield` to call it. +Если последний фактический аргумент в вызове метода является объектом `Proc`, вы можете поставить перед его именем амперсанд, чтобы преобразовать его в блок. Затем метод может использовать `yield` для его вызова. ~~~ def meth1(&b) @@ -328,7 +277,7 @@ meth2 {|i| i + i } meth2 &square ~~~ -Produces: +Результат: ~~~ 18 @@ -336,7 +285,7 @@ Produces: 64 ~~~ -### How can I specify a default value for a formal argument? +### Как я могу указать значение по умолчанию для формального аргумента? ~~~ def greet(p1="hello", p2="world") @@ -348,7 +297,7 @@ greet("hi") greet("morning", "mom") ~~~ -Produces: +Результат: ~~~ hello world @@ -356,26 +305,21 @@ hi world morning mom ~~~ -The default value (which can be an arbitrary expression) is evaluated when -the method is invoked. It is evaluated using the scope of the method. +Значение по умолчанию (которое может быть произвольным выражением) вычисляется при вызове метода. Оно вычисляется с использованием области видимости метода. -### How do I pass arguments to a block? +### Как мне передать аргументы в блок? -The formal parameters of a block appear between vertical bars at the start -of the block: +Формальные параметры блока указываются между вертикальными чертами в начале блока: ~~~ proc {|a, b| a <=> b } ~~~ -These parameters are actually local variables. If an existing local variable -of the same name exists when the block executes, that variable will be -modified by the call to the block. This may or may not be a good thing. +Эти параметры на самом деле являются локальными переменными. Если при выполнении блока существует локальная переменная с таким же именем, эта переменная будет изменена вызовом блока. Это может быть как хорошо, так и плохо. -Typically, arguments are passed to a block using `yield` (or an iterator that -calls `yield`), or by using the `Proc.call` method. +Обычно аргументы передаются в блок с помощью `yield` (или итератора, который вызывает `yield`) или с помощью метода `Proc.call`. -### Why did my object change unexpectedly? +### Почему мой объект неожиданно изменился? ~~~ A = a = b = "abc" @@ -384,45 +328,37 @@ a # => "abcd" A # => "abcd" ~~~ -Variables hold references to objects. The assignment `A = a = b = "abc"` puts -a reference to the string `"abc"` into `A`, `a`, and `b`. +Переменные хранят ссылки на объекты. Присваивание `A = a = b = "abc"` помещает ссылку на строку `"abc"` в `A`, `a` и `b`. -When you call `b.concat("d")`, you invoke the concat method on that object, -changing it from `"abc"` to `"abcd"`. Because `a` and `A` also reference that -same object, their apparent values change too. +Когда вы вызываете `b.concat("d")`, вы вызываете метод concat для этого объекта, изменяя его с `"abc"` на `"abcd"`. Поскольку `a` и `A` также ссылаются на тот же самый объект, их видимые значения тоже меняются. -This is less of a problem in practice than it might appear. +На практике это представляет меньше проблем, чем может показаться. -In addition, all objects may be frozen, protecting them from change. +Кроме того, все объекты могут быть заморожены, что защищает их от изменений. -### Does the value of a constant ever change? +### Меняется ли когда-нибудь значение константы? -A constant is a variable whose name starts with an upper case letter. -Constants may not be reassigned from within instance methods, -but can otherwise be changed at will. -When a constant is assigned a new value, a warning is issued. +Константа — это переменная, имя которой начинается с заглавной буквы. Константам нельзя переприсваивать значения из методов экземпляра, но в остальных случаях их можно менять по желанию. Когда константе присваивается новое значение, выдается предупреждение. -### Why can't I load variables from a separate file? +### Почему я не могу загрузить переменные из отдельного файла? -Say `file1.rb` contains: +Допустим, `file1.rb` содержит: ~~~ var1 = 99 ~~~ -and some other file loads it in: +и какой-то другой файл загружает его: ~~~ require_relative "file1" puts var1 ~~~ -Produces: +Результат: ~~~ prog.rb:2:in `
': undefined local variable or method `var1' for main:Object (NameError) ~~~ -You get an error because `load` and `require` arrange for local variables to -be stored into a separate, anonymous namespace, effectively discarding them. -This is designed to protect your code from being polluted. +Вы получаете ошибку, потому что `load` и `require` организуют хранение локальных переменных в отдельном анонимном пространстве имен, фактически отбрасывая их. Это сделано для защиты вашего кода от загрязнения. diff --git a/ru/documentation/faq/5/index.md b/ru/documentation/faq/5/index.md index 92650f49bd..7d7718d98b 100644 --- a/ru/documentation/faq/5/index.md +++ b/ru/documentation/faq/5/index.md @@ -1,51 +1,47 @@ --- layout: page -title: "Official Ruby FAQ" +title: "Официальный FAQ по Ruby" lang: ru header: |
- Content + Оглавление | - 1 + 1 | - 2 + 2 | - 3 + 3 | - 4 + 4 | 5 | - 6 + 6 | - 7 + 7 | - 8 + 8 | - 9 + 9 | - 10 + 10 | - 11 + 11
-

Official Ruby FAQ

+

Официальный FAQ по Ruby

--- {% include faq-notice.md %} -## Iterators +## Итераторы -### What is an iterator? +### Что такое итератор? -An iterator is a method which accepts a block or a `Proc` object. In the -source file, the block is placed immediately after the invocation of the -method. Iterators are used to produce user-defined control -structures---especially loops. +Итератор — это метод, который принимает блок или объект `Proc`. В исходном файле блок помещается сразу после вызова метода. Итераторы используются для создания пользовательских структур управления — особенно циклов. -Let's look at an example to see how this works. Iterators are often used to -repeat the same action on each element of a collection, like this: +Давайте рассмотрим пример, чтобы увидеть, как это работает. Итераторы часто используются для повторения одного и того же действия для каждого элемента коллекции, например так: ~~~ data = [1, 2, 3] @@ -54,7 +50,7 @@ data.each do |i| end ~~~ -Produces: +Результат: ~~~ 1 @@ -62,11 +58,9 @@ Produces: 3 ~~~ -The each method of the array `data` is passed the `do ... end` block, -and executes it repeatedly. On each call, the block is passed successive -elements of the array. +Методу `each` массива `data` передается блок `do ... end`, и он выполняет его многократно. При каждом вызове блоку передаются последовательные элементы массива. -You can define blocks with `{ ... }` in place of `do ... end`. +Вы можете определять блоки с помощью `{ ... }` вместо `do ... end`. ~~~ data = [1, 2, 3] @@ -75,7 +69,7 @@ data.each { |i| } ~~~ -Produces: +Результат: ~~~ 1 @@ -83,34 +77,26 @@ Produces: 3 ~~~ -This code has the same meaning as the last example. However, in some cases, -precedence issues cause `do ... end` and `{ ... }` to act differently. +Этот код имеет тот же смысл, что и в предыдущем примере. Однако в некоторых случаях из-за приоритетов операций `do ... end` и `{ ... }` ведут себя по-разному. ~~~ -foobar a, b do ... end # foobar is the iterator. -foobar a, b { ... } # b is the iterator. +foobar a, b do ... end # foobar является итератором. +foobar a, b { ... } # b является итератором. ~~~ -This is because `{ ... }` binds more tightly to the preceding expression -than does a `do ... end` block. The first example is equivalent to -`foobar(a, b) do ... end`, while the second is `foobar(a, b { ... })`. +Это происходит потому, что `{ ... }` связывается с предшествующим выражением сильнее, чем блок `do ... end`. Первый пример эквивалентен `foobar(a, b) do ... end`, а второй — `foobar(a, b { ... })`. -### How can I pass a block to an iterator? +### Как мне передать блок итератору? -You simply place the block after the iterator call. You can also pass a -`Proc` object by prepending `&` to the variable or constant name that refers -to the `Proc`. +Вы просто помещаете блок после вызова итератора. Вы также можете передать объект `Proc`, добавив `&` перед именем переменной или константы, которая ссылается на `Proc`. -### How is a block used in an iterator? +### Как блок используется в итераторе? {% include warnings/faq-out-of-date.html %} -There are three ways to execute a block from an iterator method: -(1) the `yield` control structure; (2) calling a `Proc` argument -(made from a block) with `call`; and (3) using `Proc.new` followed by a call. +Существует три способа выполнить блок из метода итератора: (1) управляющая структура `yield`; (2) вызов аргумента `Proc` (созданного из блока) с помощью `call`; и (3) использование `Proc.new`, за которым следует вызов. -The `yield` statement calls the block, optionally passing it one or more -arguments. +Инструкция `yield` вызывает блок, опционально передавая ему один или несколько аргументов. ~~~ def my_iterator @@ -120,16 +106,14 @@ end my_iterator {|a, b| puts a, b } ~~~ -Produces: +Результат: ~~~ 1 2 ~~~ -If a method definition has a block argument (the last formal parameter has -an ampersand (`&`) prepended), it will receive the attached block, converted -to a `Proc` object. This may be called using `prc.call(args)`. +Если в определении метода есть аргумент блока (перед последним формальным параметром стоит амперсанд (`&`)), он получит прикрепленный блок, преобразованный в объект `Proc`. Его можно вызвать с помощью `prc.call(args)`. ~~~ def my_iterator(&b) @@ -139,20 +123,16 @@ end my_iterator {|a, b| puts a, b } ~~~ -Produces: +Результат: ~~~ 1 2 ~~~ -`Proc.new` (or the equivalent `proc` or `lambda` calls), when used in an -iterator definition, takes the block which is given to the method as its -argument and generates a procedure object from it. -(`proc` and `lambda` are effectively synonyms.) +`Proc.new` (или эквивалентные вызовы `proc` или `lambda`) при использовании в определении итератора берет блок, переданный методу в качестве аргумента, и генерирует из него объект процедуры. (`proc` и `lambda` фактически являются синонимами). -_[Update needed: `lambda` behaves in a slightly different way and -produces a warning `tried to create Proc object without a block`.]_ +_[Требуется обновление: `lambda` ведет себя немного иначе и вызывает предупреждение `tried to create Proc object without a block`.]_ ~~~ def my_iterator @@ -164,7 +144,7 @@ end my_iterator {|a, b| puts a, b } ~~~ -Produces: +Результат: ~~~ 3 @@ -175,24 +155,17 @@ Produces: 8 ~~~ -Perhaps surprisingly, `Proc.new` and friends do not in any sense consume -the block attached to the method---each call to `Proc.new` generates a new -procedure object out of the same block. +Возможно, это удивительно, но `Proc.new` и компания ни в коем случае не «потребляют» блок, прикрепленный к методу — каждый вызов `Proc.new` генерирует новый объект процедуры из того же самого блока. -You can tell if there is a block associated with a method by calling -`block_given?`. +Вы можете узнать, связан ли с методом блок, вызвав `block_given?`. -### What does `Proc.new` without a block do? +### Что делает `Proc.new` без блока? -`Proc.new` without a block cannot generate a procedure object and an error -occurs. In a method definition, however, `Proc.new` without a block implies -the existence of a block at the time the method is called, and so no error -will occur. +`Proc.new` без блока не может сгенерировать объект процедуры, и возникает ошибка. Однако в определении метода `Proc.new` без блока подразумевает наличие блока в момент вызова метода, поэтому ошибки не возникнет. -### How can I run iterators in parallel? +### Как я могу запускать итераторы параллельно? -Here an adoption of a solution by Matz, in -[\[ruby-talk:5252\]][ruby-talk:5252], that uses threads: +Вот адаптация решения от Matz из [\[ruby-talk:5252\]][ruby-talk:5252], которое использует потоки: ~~~ require "thread" @@ -230,7 +203,7 @@ def it2 end combine(:it1, :it2) do |x| - # x is [1, 4], then [2, 5], then [3, 6] + # x это [1, 4], затем [2, 5], затем [3, 6] end ~~~ diff --git a/ru/documentation/faq/6/index.md b/ru/documentation/faq/6/index.md index 5cd8faf3eb..b58e5b9316 100644 --- a/ru/documentation/faq/6/index.md +++ b/ru/documentation/faq/6/index.md @@ -1,106 +1,81 @@ --- layout: page -title: "Official Ruby FAQ" +title: "Официальный FAQ по Ruby" lang: ru header: |
- Content + Оглавление | - 1 + 1 | - 2 + 2 | - 3 + 3 | - 4 + 4 | - 5 + 5 | 6 | - 7 + 7 | - 8 + 8 | - 9 + 9 | - 10 + 10 | - 11 + 11
-

Official Ruby FAQ

+

Официальный FAQ по Ruby

--- {% include faq-notice.md %} -## Syntax +## Синтаксис -### What is the difference between an immediate value and a reference? +### В чем разница между непосредственным значением и ссылкой? {: #immediate} {% include warnings/faq-out-of-date.html %} -`Fixnum`, `true`, `nil`, and `false` are implemented as immediate values. -With immediate values, variables hold the objects themselves, rather than -references to them. +`Fixnum`, `true`, `nil` и `false` реализованы как непосредственные (immediate) значения. В случае непосредственных значений переменные хранят сами объекты, а не ссылки на них. -Singleton methods cannot be defined for such objects. Two `Fixnums` of the -same value always represent the same object instance, so (for example) -instance variables for the `Fixnum` with the value `1` are shared between -all the `1`'s in the system. This makes it impossible to define a singleton -method for just one of these. +Для таких объектов нельзя определить синглтон-методы. Два объекта `Fixnum` с одинаковым значением всегда представляют один и тот же экземпляр объекта, поэтому (например) переменные экземпляра для `Fixnum` со значением `1` разделяются между всеми `1` в системе. Это делает невозможным определение синглтон-метода только для одного из них. -### What is the difference between `nil` and `false`? +### В чем разница между `nil` и `false`? -First the similarity: `nil` and `false` are the only two objects -that evaluate to `false` in a boolean context. -(In other words: they are the only “falsy” values, all other -objects are “truthy”.) +Сначала о сходстве: `nil` и `false` — единственные два объекта, которые в булевом контексте вычисляются как `false`. (Другими словами: это единственные «ложные» значения, все остальные объекты являются «истинными»). -However, `nil` and `false` are instances of different classes -(`NilClass` and `FalseClass`), and have different behavior elsewhere. +Однако `nil` и `false` являются экземплярами разных классов (`NilClass` и `FalseClass`) и ведут себя по-разному в остальных случаях. -We recommend that predicate methods (those whose name ends with a question -mark) return `true` or `false`. Other methods that need to indicate failure -should return `nil`. +Мы рекомендуем, чтобы предикатные методы (те, чье имя заканчивается вопросительным знаком) возвращали `true` или `false`. Другие методы, которым нужно указать на ошибку или отсутствие результата, должны возвращать `nil`. -### Why is an empty string not `false`? +### Почему пустая строка не является `false`? -Q: An empty string (`""`) returns `true` in a conditional expression! -In Perl, it's `false`. +В: Пустая строка (`""`) возвращает `true` в условном выражении! В Perl она ложна (`false`). -A: But Ruby is not Perl ;-). It's very simple: in Ruby, only `nil` -and `false` are false in conditional contexts. +О: Но Ruby — это не Perl ;-). Все очень просто: в Ruby только `nil` и `false` являются ложными в контексте условий. -You can use `empty?`, compare the string to `""`, or compare the string's -`size` or `length` to `0` to find out if a string is empty. +Вы можете использовать `empty?`, сравнивать строку с `""` или сравнивать `size` или `length` строки с `0`, чтобы узнать, пуста ли она. -### What does `:name` mean? +### Что означает `:name`? -A colon followed by a name generates a Symbol object which corresponds -one to one with the identifier. During the duration of a program's -execution the same Symbol object will be created for a given name or string. -Symbols can also be created with `"name".intern` or `"name".to_sym`. +Двоеточие, за которым следует имя, создает объект Symbol (символ), который однозначно соответствует этому идентификатору. В течение времени выполнения программы для одного и того же имени или строки будет создаваться один и тот же объект Symbol. Символы также можно создавать с помощью `"name".intern` или `"name".to_sym`. -Symbol objects can represent identifiers for methods, variables, and so on. -Some methods, like `define_method`, `method_missing`, or `trace_var`, -require a symbol. Other methods, e.g. `attr_accessor`, `send`, or `autoload`, -also accept a string. +Объекты Symbol могут представлять идентификаторы для методов, переменных и так далее. Некоторые методы, такие как `define_method`, `method_missing` или `trace_var`, требуют символ. Другие методы, например `attr_accessor`, `send` или `autoload`, также принимают строку. -Due to the fact that they are created only once, Symbols are often used as -hash keys. String hash keys would create a new object for every single use, -thereby causing some memory overhead. -There is even a special syntax for symbol hash keys: +Благодаря тому, что они создаются только один раз, символы часто используются в качестве ключей хеша. Строковые ключи хеша создавали бы новый объект при каждом использовании, что приводило бы к некоторым накладным расходам памяти. Для ключей хеша в виде символов существует даже специальный синтаксис: ~~~ person_1 = { :name => "John", :age => 42 } -person_2 = { name: "Jane", age: 24 } # alternate syntax +person_2 = { name: "Jane", age: 24 } # альтернативный синтаксис ~~~ -Symbols can also be used as enumeration values -or to assign unique values to constants: +Символы также можно использовать в качестве перечисляемых значений или для присвоения уникальных значений константам: ~~~ status = :open # :closed, ... @@ -109,11 +84,9 @@ NORTH = :NORTH SOUTH = :SOUTH ~~~ -### How can I access the value of a symbol? +### Как я могу получить доступ к значению символа? -To get the value of the variable corresponding to a symbol, you can use -`symbol.to_s` or `"#{symbol}"` to get the name of the variable, and then -eval that in the scope of the symbol to get the variable's contents: +Чтобы получить значение переменной, соответствующей символу, вы можете использовать `symbol.to_s` или `"#{symbol}"`, чтобы получить имя переменной, а затем выполнить `eval` в области видимости символа, чтобы получить содержимое переменной: ~~~ a = "This is the content of `a'" @@ -121,13 +94,13 @@ b = eval("#{:a}") a.object_id == b.object_id # => true ~~~ -You can also use +Вы также можете использовать ~~~ b = binding.local_variable_get(:a) ~~~ -If your symbol corresponds to the name of a method, you can use `send`: +Если ваш символ соответствует имени метода, вы можете использовать `send`: ~~~ class Demo @@ -140,27 +113,22 @@ demo = Demo.new demo.send(:hello) ~~~ -Or you can use `Object#method` to return a corresponding `Method` object, -which you may then call: +Или вы можете использовать `Object#method`, чтобы вернуть соответствующий объект `Method`, который затем можно вызвать: ~~~ m = demo.method(:hello) # => # m.call # => "Hello, world" ~~~ -### Is `loop` a control structure? +### Является ли `loop` структурой управления? -Although `loop` looks like a control structure, it is actually a method -defined in `Kernel`. The block which follows introduces a new scope for -local variables. +Хотя `loop` выглядит как структура управления, на самом деле это метод, определенный в `Kernel`. Следующий за ним блок вводит новую область видимости для локальных переменных. -### Ruby doesn't have a post-test loop +### В Ruby нет цикла с постусловием -Q: Ruby does not have a `do { ... } while` construct, so how can I implement -loops that test the condition at the end? +В: В Ruby нет конструкции `do { ... } while`, так как же мне реализовать циклы, проверяющие условие в конце? -Clemens Hintze says: You can use a combination of Ruby's `begin ... end` -and the `while` or `until` statement modifiers to achieve the same effect: +О: Clemens Hintze говорит: Вы можете использовать сочетание `begin ... end` и модификаторов инструкций `while` или `until` для достижения того же эффекта: ~~~ i = 0 @@ -170,7 +138,7 @@ begin end until i > 4 ~~~ -Produces: +Результат: ~~~ i = 0 @@ -180,15 +148,13 @@ i = 3 i = 4 ~~~ -### Why can't I pass a hash literal to a method: `p {}`? +### Почему я не могу передать литерал хеша в метод: `p {}`? -The `{}` is parsed as a block, not a `Hash` constructor. You can force the -`{}` to be treated as an expression by making the fact that it's a parameter -explicit: `p({})`. +`{}` парсится как блок, а не как конструктор `Hash`. Вы можете заставить `{}` рассматриваться как выражение, сделав факт того, что это параметр, явным: `p({})`. -### I can't get `def pos=(val)` to work! +### Я не могу заставить `def pos=(val)` работать! -I have the following code, but I cannot use the method `pos = 1`. +У меня есть следующий код, но я не могу использовать метод `pos = 1`. ~~~ def pos=(val) @@ -197,75 +163,62 @@ def pos=(val) end ~~~ -Methods with `=` appended must be called with an explicit receiver -(without the receiver, you are just assigning to a local variable). -Invoke it as `self.pos = 1`. +Методы с приписанным `=` должны вызываться с явным получателем (без получателя вы просто присваиваете значение локальной переменной). Вызывайте его как `self.pos = 1`. -### What is the difference between `'\1'` and `'\\1'`? +### В чем разница между `'\1'` и `'\\1'`? -They have the same meaning. In a single quoted string, only `\'` and `\\` -are transformed and other combinations remain unchanged. +Они имеют одинаковое значение. В строке в одинарных кавычках только `\'` и `\\` трансформируются, а другие комбинации остаются без изменений. -However, in a double quoted string, `"\1"` is the byte `\001` -(an octal bit pattern), while `"\\1"` is the two character string -containing a backslash and the character `"1"`. +Однако в строке в двойных кавычках `"\1"` — это байт `\001` (восьмеричный битовый паттерн), в то время как `"\\1"` — это строка из двух символов, содержащая обратный слэш и символ `"1"`. -### What is the difference between `..` and `...`? +### В чем разница между `..` и `...`? -`..` includes the right hand side in the range, `...` does not: +`..` включает правую границу в диапазон, `...` — нет: ~~~ (5..8).to_a # => [5, 6, 7, 8] (5...8).to_a # => [5, 6, 7] ~~~ -### What is the difference between `or` and `||`? +### В чем разница между `or` и `||`? -Q: `p(nil || "Hello")` prints `"Hello"`, while `p(nil or "Hello")` gives a -parse error. Why? +В: `p(nil || "Hello")` выводит `"Hello"`, в то время как `p(nil or "Hello")` выдает ошибку парсинга. Почему? -A: `or` has a very low precedence, `p( (nil or "Hello") )` will work. +О: `or` имеет очень низкий приоритет, `p( (nil or "Hello") )` будет работать. -The precedence of `or` is for instance also lower than that of `=`, -whereas `||` has a higher precedence: +Приоритет `or`, например, также ниже, чем у `=`, в то время как у `||` приоритет выше: ~~~ -foo = nil || "Hello" # parsed as: foo = (nil || "Hello") +foo = nil || "Hello" # парсится как: foo = (nil || "Hello") foo # => "Hello" -# but perhaps surprisingly: +# но, возможно, это удивительно: -foo = nil or "Hello" # parsed as: (foo = nil) or "Hello" +foo = nil or "Hello" # парсится как: (foo = nil) or "Hello" foo # => nil ~~~ -`or` (and similarly `and`) is best used **not** for combining -boolean expressions, but for control flow, like in +`or` (и аналогично `and`) лучше всего использовать **не** для объединения булевых выражений, а для управления потоком выполнения, например: ~~~ do_something or raise "some error!" ~~~ -where `do_something` returns `false` or `nil` when an error occurs. +где `do_something` возвращает `false` или `nil` при возникновении ошибки. -### Does Ruby have function pointers? +### Есть ли в Ruby указатели на функции? -A `Proc` object generated by `Proc.new`, `proc`, or `lambda` can be referenced -from a variable, so that variable could be said to be a function pointer. You -can also get references to methods within a particular object instance using -`object.method`. +Объект `Proc`, созданный с помощью `Proc.new`, `proc` или `lambda`, может быть доступен через переменную, так что эту переменную можно назвать указателем на функцию. Вы также можете получить ссылки на методы внутри конкретного экземпляра объекта, используя `object.method`. -### What is the difference between `load` and `require`? +### В чем разница между `load` и `require`? -`load` will load and execute a Ruby program (`*.rb`). +`load` загружает и выполняет программу на Ruby (`*.rb`). -`require` loads Ruby programs as well, but will also load binary Ruby -extension modules (shared libraries or DLLs). In addition, -`require` ensures that a feature is never loaded more than once. +`require` также загружает программы на Ruby, но кроме того загружает бинарные модули расширения Ruby (разделяемые библиотеки или DLL). В дополнение к этому, `require` гарантирует, что функциональность никогда не будет загружена более одного раза. -### Does Ruby have exception handling? +### Есть ли в Ruby обработка исключений? -Ruby supports a flexible exception handling scheme: +Ruby поддерживает гибкую схему обработки исключений: ~~~ begin @@ -279,15 +232,10 @@ ensure end ~~~ -If an exception occurs in the `begin` clause, the `rescue` clause with the -matching exception name is executed. The `ensure` clause is executed whether -an exception occurred or not. `rescue` and `ensure` clauses may be omitted. +Если в блоке `begin` возникает исключение, выполняется блок `rescue` с соответствующим именем исключения. Блок `ensure` выполняется независимо от того, возникло исключение или нет. Блоки `rescue` и `ensure` могут быть опущены. -If no exception class is designated for a `rescue` clause, `StandardError` -exception is implied, and exceptions which are in a `is_a?` relation to -`StandardError` are captured. +Если для блока `rescue` не указан класс исключения, подразумевается исключение `StandardError`, и перехватываются исключения, находящиеся в отношении `is_a?` к `StandardError`. -This expression returns the value of the `begin` clause. +Это выражение возвращает значение блока `begin`. -The latest exception is accessed by the global variable `$!` -(and so its type can be determined using `$!.type`). +Последнее исключение доступно через глобальную переменную `$!` (и, таким образом, его тип можно определить с помощью `$!.type`). diff --git a/ru/documentation/faq/7/index.md b/ru/documentation/faq/7/index.md index 7771d3ce23..0ce0d408e7 100644 --- a/ru/documentation/faq/7/index.md +++ b/ru/documentation/faq/7/index.md @@ -1,55 +1,47 @@ --- layout: page -title: "Official Ruby FAQ" +title: "Официальный FAQ по Ruby" lang: ru header: |
- Content + Оглавление | - 1 + 1 | - 2 + 2 | - 3 + 3 | - 4 + 4 | - 5 + 5 | - 6 + 6 | 7 | - 8 + 8 | - 9 + 9 | - 10 + 10 | - 11 + 11
-

Official Ruby FAQ

+

Официальный FAQ по Ruby

--- {% include faq-notice.md %} -## Methods +## Методы -### How does Ruby choose which method to invoke? +### Как Ruby выбирает, какой метод вызвать? -Ruby binds all messages to methods dynamically. It searches first for -singleton methods in the receiver, then for methods defined in the receiver's -own class, and finally for methods defined in the receiver's superclasses -(including any modules which may have been mixed in). You can see the order -of searching by displaying `ClassName.ancestors`, which shows the ancestor -classes and modules of `ClassName`. +Ruby связывает все сообщения с методами динамически. Сначала он ищет синглтон-методы у получателя, затем методы, определенные в собственном классе получателя, и, наконец, методы, определенные в суперклассах получателя (включая любые модули, которые могли быть подмешаны). Вы можете увидеть порядок поиска, выведя `ClassName.ancestors`, который показывает классы-предки и модули `ClassName`. -If after searching the alternatives a matching method could not be found, -Ruby tries to invoke a method called `method_missing`, repeating the same -search procedure to find it. This allows you to handle messages to unknown -methods, and is often used to provide dynamic interfaces to classes. +Если после поиска альтернатив подходящий метод не был найден, Ruby пытается вызвать метод с именем `method_missing`, повторяя ту же процедуру поиска для его нахождения. Это позволяет вам обрабатывать сообщения к неизвестным методам и часто используется для предоставления динамических интерфейсов классам. ~~~ module Emphasizable @@ -68,12 +60,9 @@ String.ancestors "Wow!".emphasize # => "**Wow!**" ~~~ -When the method `emphasize` is searched for, it is not found in class -`String`, so Ruby searches next in the module `Emphasizable`. +Когда ищется метод `emphasize`, он не обнаруживается в классе `String`, поэтому Ruby ищет далее в модуле `Emphasizable`. -In order to override a method that already exists in the receiver's class, -e.g. `String#capitalize`, you need to insert the module into the -ancestor chain in front of that class, by using `prepend`: +Для того чтобы переопределить метод, который уже существует в классе получателя, например `String#capitalize`, вам нужно вставить модуль в цепочку предков перед этим классом, используя `prepend`: ~~~ module PrettyCapitalize @@ -92,10 +81,9 @@ String.ancestors "hello".capitalize # => "**Hello**" ~~~ -### Are `+`, `-`, `*`, ... operators? +### Являются ли `+`, `-`, `*`, ... операторами? -`+`, `-`, and the like are not operators but method calls. -They can, therefore, be overloaded by new definitions. +`+`, `-` и тому подобные являются не операторами, а вызовами методов. Поэтому они могут быть перегружены новыми определениями. ~~~ class MyString < String @@ -105,17 +93,15 @@ class MyString < String end ~~~ -However, the following are built-in control structures, not methods, -which cannot be overridden: +Однако следующие являются встроенными структурами управления, а не методами, и их нельзя переопределить: ~~~ =, .., ..., not, ||, &&, and, or, :: ~~~ -To overload or to define the unary `+` and `-` operators, -you need to use `+@` and `-@` as the method names. +Чтобы перегрузить или определить унарные операторы `+` и `-`, вам нужно использовать `+@` и `-@` в качестве имен методов. -`=` is used to define a method to set an attribute of the object: +`=` используется для определения метода установки атрибута объекта: ~~~ class Test @@ -128,20 +114,18 @@ t = Test.new t.attribute = 1 ~~~ -If operators such as `+` and `-` are defined, Ruby automatically handles -the self assignment forms (`+=`, `-=`, and so on). +Если определены такие операторы, как `+` и `-`, Ruby автоматически обрабатывает формы самоприсваивания (`+=`, `-=`, и так далее). -### Where are `++` and `--` ? +### Где `++` и `--` ? -Ruby does not have the autoincrement and autodecrement operators. -You can use `+= 1` and `-= 1` instead. +В Ruby нет операторов автоинкремента и автодекремента. Вместо них вы можете использовать `+= 1` и `-= 1`. -### What is a singleton method? +### Что такое синглтон-метод? {: #singleton-method} -A singleton method is an instance method associated with one specific object. +Синглтон-метод (singleton method) — это метод экземпляра, связанный с одним конкретным объектом. -You create a singleton method by including the object in the definition: +Вы создаете синглтон-метод, включая объект в определение: ~~~ class Foo; end @@ -157,20 +141,18 @@ foo.hello bar.hello ~~~ -Produces: +Результат: ~~~ Hello -prog.rb:11:in `
': undefined method `hello' for # (NoMethodError) +prog.rb:11:in `
': undefined method `hello' for # (NameError) ~~~ -Singleton methods are useful when you want to add a method to an object and -creating a new subclass is not appropriate. +Синглтон-методы полезны, когда вы хотите добавить метод к объекту, а создание нового подкласса нецелесообразно. -### All these objects are fine, but does Ruby have any simple functions? +### Все эти объекты — это прекрасно, но есть ли в Ruby обычные функции? -Yes and no. Ruby has methods that look like functions in languages such -as C or Perl: +И да, и нет. В Ruby есть методы, которые выглядят как функции в таких языках, как C или Perl: ~~~ def hello(name) @@ -180,38 +162,27 @@ end hello("World") ~~~ -Produces: +Результат: ~~~ Hello, World! ~~~ -However, they are actually method calls with the receiver omitted. -In this case, Ruby assumes the receiver is self. +Однако на самом деле это вызовы методов с опущенным получателем. В этом случае Ruby предполагает, что получателем является `self`. -So, `hello` resembles a function but it's actually a method belonging to -class `Object` and sent as a message to the hidden receiver self. -Ruby is a pure object-oriented language. +Таким образом, `hello` напоминает функцию, но на самом деле это метод, принадлежащий классу `Object` и отправляемый как сообщение скрытому получателю `self`. Ruby — это чистый объектно-ориентированный язык. -Of course you can use such methods as if they were functions. +Конечно, вы можете использовать такие методы, как если бы они были функциями. -### So where do all these function-like methods come from? +### Откуда же берутся все эти методы, похожие на функции? -Almost all classes in Ruby are derived from class `Object`. The definition -of class `Object` mixes in the methods defined in the `Kernel` module. -These methods are therefore available within every object in the system. +Почти все классы в Ruby производны от класса `Object`. Определение класса `Object` подмешивает методы, определенные в модуле `Kernel`. Таким образом, эти методы доступны внутри каждого объекта в системе. -Even if you are writing a simple Ruby program without classes, you are -actually working inside class `Object`. +Даже если вы пишете простую программу на Ruby без классов, вы на самом деле работаете внутри класса `Object`. -### Can I access an object's instance variables? +### Могу ли я получить доступ к переменным экземпляра объекта? -An object's instance variables (those variables starting with `@`) are not -directly accessible outside the object. This promotes good encapsulation. -However, Ruby makes it easy for you to define accessors to these instance -variables in such a way that users of your class can treat instance variables -just like attributes. Just use one or more of `attr_reader`, `attr_writer`, -or `attr_accessor`. +Переменные экземпляра объекта (те переменные, которые начинаются с `@`) недоступны напрямую вне объекта. Это способствует хорошей инкапсуляции. Однако Ruby позволяет вам легко определять аксессоры (accessors) к этим переменным экземпляра таким образом, чтобы пользователи вашего класса могли обращаться с переменными экземпляра так же, как с атрибутами. Просто используйте один или несколько из `attr_reader`, `attr_writer` или `attr_accessor`. ~~~ class Person @@ -230,21 +201,11 @@ p.wearing_a_hat = true p.wearing_a_hat # => true ~~~ -You can also define your own accessor functions (perhaps to perform -validation, or to handle derived attributes). The read accessor is simply a -method that takes no parameters, and the assignment accessor is a method name -ending in `=` that takes a single parameter. Although there can be no space -between the method name and the `=` in the method definition, you can insert -spaces there when you call the method, making it look like any other -assignment. You can also utilize self assignments such as `+=` and `-=`, -as long as the corresponding `+` or `-` methods are defined. +Вы также можете определить свои собственные функции доступа (возможно, для выполнения валидации или обработки производных атрибутов). Аксессор для чтения — это просто метод без параметров, а аксессор для присваивания — это имя метода, заканчивающееся на `=`, который принимает один параметр. Хотя в определении метода между именем метода и `=` не может быть пробела, вы можете вставлять пробелы при вызове метода, что делает его похожим на любое другое присваивание. Вы также можете использовать самоприсваивания, такие как `+=` и `-=`, при условии, что определены соответствующие методы `+` или `-`. -### What's the difference between `private` and `protected`? +### В чем разница между `private` и `protected`? -The visibility keyword `private` makes a method callable only in a function -form, without an explicit receiver, and so it can only have `self` as its -receiver. A private method is callable only within the class in which the -method was defined or in its subclasses. +Ключевое слово видимости `private` делает метод вызываемым только в форме функции, без явного получателя, и поэтому он может иметь только `self` в качестве своего получателя. Приватный метод можно вызвать только внутри класса, в котором этот метод был определен, или в его подклассах. ~~~ class Test @@ -272,7 +233,7 @@ end t1.test(t2) ~~~ -Produces: +Результат: ~~~ 99 @@ -282,9 +243,7 @@ prog.rb:8:in `test': private method `foo' called for # (N from prog.rb:23:in `
' ~~~ -Protected methods are also callable only from within their own class or -its subclasses, but they can be called both in function form and using -a receiver. For example: +Защищенные (protected) методы также можно вызвать только из их собственного класса или его подклассов, но их можно вызывать как в форме функции, так и с использованием получателя. Например: ~~~ def <=>(other) @@ -292,16 +251,13 @@ def <=>(other) end ~~~ -Will compile if `age` is a protected method, but not if it is private. +Скомпилируется, если `age` — защищенный метод, но не если он приватный. -These features help you control access to your class's internals. +Эти возможности помогают вам контролировать доступ к внутренностям вашего класса. -### How can I change the visibility of a method? +### Как я могу изменить видимость метода? -You change the visibility of methods using `private`, `protected`, and -`public`. When used without parameters during a class definition, they affect -the visibility of subsequent methods. When used with parameters, they change -the visibility of the named methods. +Вы меняете видимость методов, используя `private`, `protected` и `public`. Когда они используются без параметров в определении класса, они влияют на видимость последующих методов. При использовании с параметрами они изменяют видимость указанных методов. ~~~ class Foo @@ -315,13 +271,13 @@ foo = Foo.new foo.test ~~~ -Produces: +Результат: ~~~ prog.rb:9:in `
': private method `test' called for # (NoMethodError) ~~~ -You can make a class method private using `private_class_method`. +Вы можете сделать метод класса приватным, используя `private_class_method`. ~~~ class Foo @@ -334,68 +290,42 @@ end Foo.test ~~~ -Produces: +Результат: ~~~ prog.rb:8:in `
': private method `test' called for Foo:Class (NoMethodError) ~~~ -The default visibility for the methods defined in a class is public. -The exception is the instance initializing method, `initialize`. +По умолчанию видимость методов, определенных в классе, является публичной (`public`). Исключением является метод инициализации экземпляра `initialize`. -Methods defined at the toplevel are also public by default. +Методы, определенные на верхнем уровне, также являются публичными по умолчанию. -### Can an identifier beginning with a capital letter be a method name? +### Может ли идентификатор, начинающийся с заглавной буквы, быть именем метода? -Yes, it can, but we don't do it lightly! If Ruby sees a capitalized name -followed by a space, it will probably (depending on the context) assume it's -a constant, not a method name. So, if you use capitalized method names, -always remember to put parameter lists in parentheses, and always put the -parentheses next to the method name with no intervening spaces. -(This last suggestion is a good idea anyway!) +Да, может, но мы не делаем этого просто так! Если Ruby видит имя с большой буквы, за которым следует пробел, он, вероятно (в зависимости от контекста), предположит, что это константа, а не имя метода. Поэтому, если вы используете имена методов с большой буквы, всегда помните о том, что списки параметров нужно заключать в скобки, и всегда ставьте скобки сразу после имени метода без пробелов. (Этот последний совет полезен в любом случае!) -### Calling `super` gives an `ArgumentError`. +### Вызов `super` выдает `ArgumentError`. -Invoking `super` with no parameters in a method passes all the arguments of -that method to a method of the same name in a superclass. If the number of -arguments to the original method disagrees with that of the higher-level -method, an `ArgumentError` is raised. To get around this, simply call `super` -and pass a suitable number of arguments. +Вызов `super` без параметров в методе передает все аргументы этого метода методу с тем же именем в суперклассе. Если количество аргументов в исходном методе не совпадает с количеством аргументов в методе более высокого уровня, возникает ошибка `ArgumentError`. Чтобы обойти это, просто вызовите `super` и передайте подходящее количество аргументов. -### How can I call the method of the same name two levels up? +### Как я могу вызвать метод с тем же именем на два уровня выше? -`super` invokes the same named method one level up. If you are overloading a -method in a more distant ancestor, use `alias` to give it a new name before -masking it with your method definition. You can then call it using that -aliased name. +`super` вызывает одноименный метод на один уровень выше. Если вы перегружаете метод у более далекого предка, используйте `alias`, чтобы дать ему новое имя перед тем, как скрыть его своим определением метода. Затем вы сможете вызвать его по этому новому имени. -### How can I invoke an original built-in method after redefining it? +### Как я могу вызвать оригинальный встроенный метод после его переопределения? -Within the method definition, you can use `super`. You can also use `alias` -to give it an alternative name. Finally, you can call the original method as -a singleton method of `Kernel`. +Внутри определения метода вы можете использовать `super`. Также вы можете использовать `alias`, чтобы дать ему альтернативное имя. Наконец, вы можете вызвать оригинальный метод как синглтон-метод `Kernel`. -### What is a destructive method? +### Что такое деструктивный метод? {: #destructive-method} -A destructive method is one which alters the state of an object. `String`, -`Array`, `Hash`, and others have such methods. Often there are two -versions of a method, one with a plain name, the other with the same name, -but followed by `!`. The plain version creates a copy of the receiver, makes -its change to it, and returns the copy. The “bang” version (with the `!`) -modifies the receiver in place. +Деструктивный метод — это метод, который изменяет состояние объекта. `String`, `Array`, `Hash` и другие имеют такие методы. Часто существуют две версии метода: одна с обычным именем, другая с тем же именем, но с восклицательным знаком `!` в конце. Обычная версия создает копию получателя, вносит в неё изменения и возвращает копию. Версия с восклицательным знаком (с `!`) модифицирует получателя на месте. -Beware, however, that there are a fair number of destructive methods that -do not have an `!`, including assignment methods (`name=`), array assignment -(`[]=`), and methods such as `Array.delete`. +Однако имейте в виду, что существует немало деструктивных методов, у которых нет `!`, включая методы присваивания (`name=`), присваивание в массив (`[]=`) и такие методы, как `Array.delete`. -### Why can destructive methods be dangerous? +### Почему деструктивные методы могут быть опасны? -Remember that assignment in most cases just copies object references, and that -parameter passing is equivalent to assignment. This means you can end up with -multiple variables referencing the same object. If one of those variables is -used to invoke a destructive method, the object referenced by all of them will -be changed. +Помните, что присваивание в большинстве случаев просто копирует ссылки на объекты, и что передача параметров эквивалентна присваиванию. Это означает, что у вас может оказаться несколько переменных, ссылающихся на один и тот же объект. Если одна из этих переменных используется для вызова деструктивного метода, объект, на который ссылаются все они, будет изменен. ~~~ def foo(str) @@ -407,11 +337,11 @@ foo(obj) # => "baz" obj # => "baz" ~~~ -In this case the actual argument is altered. +В этом случае фактический аргумент изменяется. -### Can I return multiple values from a method? +### Могу ли я вернуть несколько значений из метода? -Yes and no. +И да, и нет. ~~~ def m1 @@ -426,9 +356,7 @@ m1 # => [1, 2, 3] m2 # => [1, 2, 3] ~~~ -So, only one thing is returned, but that thing can be an arbitrarily complex -object. In the case of arrays, you can use multiple assignment to get the -effect of multiple return values. For example: +Таким образом, возвращается только одна вещь, но эта вещь может быть сколь угодно сложным объектом. В случае массивов вы можете использовать множественное присваивание для получения эффекта возврата нескольких значений. Например: ~~~ def foo diff --git a/ru/documentation/faq/8/index.md b/ru/documentation/faq/8/index.md index eb2a27de8b..f2d6f163a0 100644 --- a/ru/documentation/faq/8/index.md +++ b/ru/documentation/faq/8/index.md @@ -1,51 +1,49 @@ --- layout: page -title: "Official Ruby FAQ" +title: "Официальный FAQ по Ruby" lang: ru header: |
- Content + Оглавление | - 1 + 1 | - 2 + 2 | - 3 + 3 | - 4 + 4 | - 5 + 5 | - 6 + 6 | - 7 + 7 | 8 | - 9 + 9 | - 10 + 10 | - 11 + 11
-

Official Ruby FAQ

+

Официальный FAQ по Ruby

--- {% include faq-notice.md %} -## Classes and modules +## Классы и модули -### Can a class definition be repeated? +### Может ли определение класса повторяться? -A class can be defined repeatedly. Each definition is added to the last -definition. If a method is redefined, the former one is overridden and lost. +Класс можно определять многократно. Каждое определение добавляется к предыдущему. Если метод переопределяется, старый метод замещается и теряется. -### Are there class variables? +### Существуют ли переменные класса? -There are. A variable prefixed with two at signs (`@@`) is a class variable, -accessible within both instance and class methods of the class. +Да. Переменная с префиксом из двух символов «собака» (`@@`) — это переменная класса, доступная как в методах экземпляра, так и в методах класса. ~~~ class Entity @@ -72,12 +70,11 @@ entities[6].who_am_i # => "I'm 7 of 9" Entity.total # => 9 ~~~ -However, you probably should use _class instance variables_ instead. +Однако вам, вероятно, стоит использовать _переменные экземпляра класса_ (class instance variables) вместо них. -### What is a class instance variable? +### Что такое переменная экземпляра класса? -Here the example of the previous section rewritten -using a class instance variable: +Вот пример из предыдущего раздела, переписанный с использованием переменной экземпляра класса: ~~~ class Entity @@ -109,24 +106,15 @@ Entity.instances # => 9 Entity.total # => 9 ~~~ -Here, `@instances` is a _class_ instance variable. It does not belong -to an instance of class `Entity`, but to the class object `Entity`, -which is an instance of class `Class`. +Здесь `@instances` — это переменная экземпляра _класса_. Она принадлежит не экземпляру класса `Entity`, а самому объекту класса `Entity`, который является экземпляром класса `Class`. -Class instance variables are directly accessible only within class methods -of the class. +Переменные экземпляра класса доступны напрямую только внутри методов класса. -### What is the difference between class variables and class instance variables? +### В чем разница между переменными класса и переменными экземпляра класса? -The main difference is the behavior concerning inheritance: -class variables are shared between a class and all its subclasses, -while class instance variables only belong to one specific class. +Основное различие заключается в поведении при наследовании: переменные класса разделяются между классом и всеми его подклассами, в то время как переменные экземпляра класса принадлежат только одному конкретному классу. -Class variables in some way can be seen as global variables within -the context of an inheritance hierarchy, with all the problems -that come with global variables. -For instance, a class variable might (accidentally) be reassigned -by any of its subclasses, affecting all other classes: +Переменные класса в некотором роде можно рассматривать как глобальные переменные в контексте иерархии наследования со всеми вытекающими проблемами. Например, переменная класса может быть (случайно) переприсвоена любым из подклассов, что повлияет на все остальные классы: ~~~ class Woof @@ -148,8 +136,7 @@ LoudWoof.sound # => "WOOF" Woof.sound # => "WOOF" (!) ~~~ -Or, an ancestor class might later be reopened and changed, -with possibly surprising effects: +Или класс-предок может быть позже открыт заново и изменен, что приведет к неожиданным эффектам: ~~~ class Foo @@ -170,22 +157,16 @@ end Foo.var # => "object" (!) ~~~ -So, unless you exactly know what you are doing and explicitly need -this kind of behavior, you better should use class instance variables. +Поэтому, если вы точно не знаете, что делаете, и вам не требуется именно такое поведение, лучше использовать переменные экземпляра класса. -### Does Ruby have class methods? +### Есть ли в Ruby методы класса? {: #class-method} -A [singleton method](../7/#singleton-method) of a class object is called a -class method. -(Actually, the class method is defined in the metaclass, but that is pretty -much transparent). Another way of looking at it is to say that a class method -is a method whose receiver is a class. +[Синглтон-метод](../7/#singleton-method) объекта класса называется методом класса. (На самом деле метод класса определяется в метаклассе, но это происходит практически незаметно). Другой способ взглянуть на это — сказать, что метод класса — это метод, получателем которого является класс. -It all comes down to the fact that you can call class methods without having -to have instances of that class (objects) as the receiver. +Все сводится к тому, что вы можете вызывать методы класса, не имея экземпляров этого класса (объектов) в качестве получателя. -Let's create a singleton method of class `Foo`: +Давайте создадим синглтон-метод класса `Foo`: ~~~ class Foo @@ -199,18 +180,15 @@ end Foo.test # => "this is foo" ~~~ -In this example, `Foo.test` is a class method. +В этом примере `Foo.test` является методом класса. -Instance methods which are defined in class `Class` can be used -as class methods for every(!) class. +Методы экземпляра, определенные в классе `Class`, могут использоваться как методы класса для каждого(!) класса. -### What is a singleton class? +### Что такое синглтон-класс? -A singleton class is an anonymous class that is created by subclassing the -class associated with a particular object. Singleton classes are another -way of extending the functionality associated with just one object. +Синглтон-класс (singleton class) — это анонимный класс, который создается путем наследования класса, связанного с конкретным объектом. Синглтон-классы — это еще один способ расширения функциональности только одного объекта. -Take the lowly `Foo`: +Возьмем скромный `Foo`: ~~~ class Foo @@ -223,8 +201,7 @@ foo = Foo.new foo.hello # => "hello" ~~~ -Now let's say we need to add class-level functionality to just this one -instance: +Теперь допустим, нам нужно добавить функциональность на уровне класса только для этого одного экземпляра: ~~~ class << foo @@ -240,30 +217,26 @@ foo.hello # => "hello, I'm Tom" Foo.new.hello # => "hello" ~~~ -We've customized `foo` without changing the characteristics of `Foo`. +Мы настроили `foo` без изменения характеристик `Foo`. -### What is a module function? +### Что такое функция модуля? {% include warnings/faq-out-of-date.html %} -A module function is a private, singleton method defined in a module. -In effect, it is similar to a [class method](#class-method), -in that it can be called using the `Module.method` notation: +Функция модуля — это приватный синглтон-метод, определенный в модуле. По сути, она похожа на [метод класса](#class-method) тем, что её можно вызвать с использованием нотации `Module.method`: ~~~ Math.sqrt(2) # => 1.414213562 ~~~ -However, because modules can be mixed in to classes, module functions can -also be used without the prefix (that's how all those `Kernel` functions are -made available to objects): +Однако, поскольку модули могут быть подмешаны в классы, функции модуля также могут использоваться без префикса (именно так все функции `Kernel` становятся доступными объектам): ~~~ include Math sqrt(2) # => 1.414213562 ~~~ -Use `module_function` to make a method a module function. +Используйте `module_function`, чтобы сделать метод функцией модуля. ~~~ module Test @@ -274,37 +247,27 @@ module Test end ~~~ -### What is the difference between a class and a module? +### В чем разница между классом и модулем? -Modules are collections of methods and constants. They cannot generate -instances. Classes may generate instances (objects), and have per-instance -state (instance variables). +Модули — это коллекции методов и констант. Они не могут создавать экземпляры. Классы могут создавать экземпляры (объекты) и имеют состояние для каждого экземпляра (переменные экземпляра). -Modules may be mixed in to classes and other modules. The mixed in module's -constants and methods blend into that class's own, augmenting the class's -functionality. Classes, however, cannot be mixed in to anything. +Модули могут быть подмешаны (mixed in) в классы и другие модули. Константы и методы подмешанного модуля смешиваются с собственными константами и методами класса, дополняя его функциональность. Однако классы нельзя подмешить во что-либо. -A class may inherit from another class, but not from a module. +Класс может наследоваться от другого класса, но не от модуля. -A module may not inherit from anything. +Модуль не может наследоваться ни от чего. -### Can you subclass modules? +### Можно ли создавать подклассы модулей? -No. However, a module may be included in a class or another module to mimic -multiple inheritance (the mixin facility). +Нет. Однако модуль может быть включен в класс или другой модуль, чтобы имитировать множественное наследование (механизм примесей). -This does not generate a subclass (which would require inheritance), but does -generate an `is_a?` relationship between the class and the module. +Это не создает подкласс (для чего потребовалось бы наследование), но создает отношение `is_a?` между классом и модулем. -### Give me an example of a mixin +### Дайте мне пример примеси (mixin) -The module `Comparable` provides a variety of comparison operators -(`<`, `<=`, `==`, `>=`, `>`, `between?`). It defines these in terms -of calls to the general comparison method, `<=>`. However, it does -not itself define `<=>`. +Модуль `Comparable` предоставляет различные операторы сравнения (`<`, `<=`, `==`, `>=`, `>`, `between?`). Он определяет их через вызовы общего метода сравнения `<=>`. Однако сам он не определяет `<=>`. -Say you want to create a class where comparisons are based on the number of -legs an animal has: +Допустим, вы хотите создать класс, в котором сравнение основано на количестве ног у животного: ~~~ class Animal @@ -336,16 +299,11 @@ p.between?(s, c) # => true [p, s, c].sort # => [snake, parrot, cat] ~~~ -All `Animal` must do is define its own semantics for the operator `<=>`, -and mix in the `Comparable` module. `Comparable`'s methods now become -indistinguishable from `Animal`'s and your class suddenly sprouts new -functionality. And because the same `Comparable` module is used by many -classes, your new class will share a consistent and well understood semantics. +Все, что должен сделать `Animal`, — это определить собственную семантику для оператора `<=>` и подмешить модуль `Comparable`. Методы `Comparable` теперь становятся неотличимы от методов `Animal`, и ваш класс внезапно обретает новую функциональность. А поскольку один и тот же модуль `Comparable` используется многими классами, ваш новый класс будет иметь согласованную и понятную семантику. -### Why are there two ways of defining class methods? +### Почему существует два способа определения методов класса? -You can define a class method in the class definition, and you can define -a class method at the top level. +Вы можете определить метод класса внутри определения класса или на верхнем уровне. ~~~ class Demo @@ -357,22 +315,16 @@ def Demo.another_class_method end ~~~ -There is only one significant difference between the two. -In the class definition you can refer to the class's constants directly, -as the constants are within scope. At the top level, you have to use the -`Class::CONST` notation. +Между ними есть только одно существенное различие. В определении класса вы можете обращаться к константам класса напрямую, так как они находятся в области видимости. На верхнем уровне вам придется использовать нотацию `Class::CONST`. -### What is the difference between `include` and `extend`? +### В чем разница между `include` и `extend`? {% include warnings/faq-out-of-date.html %} -`include` mixes a module into a class or another module. Methods from that -module are called function-style (without a receiver). +`include` подмешивает модуль в класс или другой модуль. Методы из этого модуля вызываются в стиле функций (без получателя). -`extend` is used to include a module in an object (instance). -Methods in the module become methods in the object. +`extend` используется для включения модуля в объект (экземпляр). Методы модуля становятся методами объекта. -### What does `self` mean? +### Что означает `self`? -`self` is the currently executing receiver, the object to which a method -is applied. A function-style method call implies `self` as the receiver. +`self` — это текущий исполняемый получатель, объект, к которому применяется метод. Вызов метода в стиле функции подразумевает `self` в качестве получателя. diff --git a/ru/documentation/faq/9/index.md b/ru/documentation/faq/9/index.md index 6170dd8552..88f87579a9 100644 --- a/ru/documentation/faq/9/index.md +++ b/ru/documentation/faq/9/index.md @@ -1,65 +1,55 @@ --- layout: page -title: "Official Ruby FAQ" +title: "Официальный FAQ по Ruby" lang: ru header: |
- Content + Оглавление | - 1 + 1 | - 2 + 2 | - 3 + 3 | - 4 + 4 | - 5 + 5 | - 6 + 6 | - 7 + 7 | - 8 + 8 | 9 | - 10 + 10 | - 11 + 11
-

Official Ruby FAQ

+

Официальный FAQ по Ruby

--- {% include faq-notice.md %} -## Built-in libraries +## Встроенные библиотеки -### What does `instance_methods(false)` return? +### Что возвращает `instance_methods(false)`? -The method `instance_methods` returns an array containing the names of -instance methods in the receiving class or module. This will include -the methods in superclasses and in mixed in modules. +Метод `instance_methods` возвращает массив, содержащий имена методов экземпляра в получающем классе или модуле. Сюда входят методы в суперклассах и в подмешанных модулях. -`instance_methods(false)` or `instance_methods(nil)` returns the names -of just those methods which are defined in the receiver. +`instance_methods(false)` или `instance_methods(nil)` возвращает имена только тех методов, которые определены в самом получателе. -### How do random number seeds work? +### Как работают начальные числа (seeds) для случайных чисел? -If `rand` is called without a prior call to `srand`, -Ruby's pseudo-random number generator uses a random(ish) seed that -amongst other things uses an entropy source provided by the OS, -if available. -Successive runs of a program that does not use `srand` will generate -different sequences of random numbers. +Если вы вызываете `rand` без предварительного вызова `srand`, генератор псевдослучайных чисел Ruby использует случайное (или близкое к нему) начальное число, которое, помимо прочего, использует источник энтропии, предоставляемый ОС, если он доступен. Последовательные запуски программы, которая не использует `srand`, будут генерировать разные последовательности случайных чисел. -For testing purposes, you can get a predictable behavior with the same -series of numbers each time the program is run by calling `srand` -with a constant seed. +Для целей тестирования вы можете получить предсказуемое поведение с одной и той же серией чисел при каждом запуске программы, вызвав `srand` с константным начальным числом. -### I read a file and changed it, but the file on disk has not changed. +### Я прочитал файл и изменил его, но файл на диске не изменился. ~~~ File.open("example", "r+").readlines.each_with_index do |line, i| @@ -67,11 +57,7 @@ File.open("example", "r+").readlines.each_with_index do |line, i| end ~~~ -This program does _not_ add line numbers to the file `example`. It does read -the contents of the file, and for each line read does prepend the line number, -but the data is never written back. The code below _does_ update the file -(although somewhat dangerously, as it takes no backup before starting the -update): +Эта программа _не_ добавляет номера строк в файл `example`. Она считывает содержимое файла и для каждой прочитанной строки добавляет номер строки в начало, но данные никогда не записываются обратно. Приведенный ниже код _обновляет_ файл (хотя и несколько рискованно, так как он не делает резервную копию перед началом обновления): ~~~ File.open("example", "r+") do |f| @@ -82,23 +68,21 @@ File.open("example", "r+") do |f| end ~~~ -### How can I process a file and update its contents? +### Как я могу обработать файл и обновить его содержимое? -Using the command-line option `-i`, or built-in variable `$-i`, you can read -a file and replace it. +Используя опцию командной строки `-i` или встроенную переменную `$-i`, вы можете прочитать файл и заменить его. -The code in the preceding question, which added line numbers to a file, -is probably best written using this technique: +Код из предыдущего вопроса, который добавлял номера строк в файл, вероятно, лучше всего написать с использованием этой техники: ~~~ $ ruby -i -ne 'print "#$.: #$_"' example ~~~ -If you want to preserve the original file, use `-i.bak` to create a backup. +Если вы хотите сохранить исходный файл, используйте `-i.bak` для создания резервной копии. -### I wrote a file, copied it, but the end of the copy seems to be lost. +### Я записал файл, скопировал его, но конец копии, похоже, потерян. -This code will not work correctly: +Этот код не будет работать корректно: ~~~ require "fileutils" @@ -107,12 +91,9 @@ File.open("file", "w").puts "This is a file." FileUtils.cp("file", "newfile") ~~~ -Because I/O is buffered, `file` is being copied before its contents have been -written to disk. `newfile` will probably be empty. However, when the program -terminates, the buffers are flushed, and file has the expected content. +Поскольку ввод-вывод буферизуется, `file` копируется до того, как его содержимое будет записано на диск. `newfile`, скорее всего, будет пустым. Однако, когда программа завершается, буферы сбрасываются (flushed), и файл обретает ожидаемое содержимое. -The problem doesn't arise if you make sure that `file` is closed before -copying: +Проблема не возникает, если вы убедитесь, что файл `file` закрыт перед копированием: ~~~ require "fileutils" @@ -121,15 +102,11 @@ File.open("file", "w") {|f| f.puts "This is a file." } FileUtils.cp("file", "newfile") ~~~ -### How can I get the line number in the current input file? +### Как я могу получить номер строки в текущем входном файле? -As you read from a file, Ruby increments a line number counter in the global -variable `$.`. This is also available using the `lineno` attribute of the -`File` object. +По мере чтения из файла Ruby увеличивает счетчик номеров строк в глобальной переменной `$.`. Он также доступен через атрибут `lineno` объекта `File`. -The special constant `ARGF` is a file-like object that can be used to read -all the input files specified on the command line (or standard input if there -are no files). `ARGF` is used implicitly by code such as: +Специальная константа `ARGF` — это объект, похожий на файл, который можно использовать для чтения всех входных файлов, указанных в командной строке (или стандартного ввода, если файлов нет). `ARGF` используется неявно в коде вида: ~~~ while gets @@ -137,40 +114,35 @@ while gets end ~~~ -In this case, `$.` will be the cumulative number of lines read across all -input files. To get the line number in the current file, use +В этом случае `$.` будет кумулятивным количеством строк, прочитанных во всех входных файлах. Чтобы получить номер строки в текущем файле, используйте: ~~~ ARGF.file.lineno ~~~ -You can also get the name of the current file using `ARGF.file.path`. +Вы также можете получить имя текущего файла с помощью `ARGF.file.path`. -### How can I use `less` to display my program's output? +### Как я могу использовать `less` для отображения вывода моей программы? -I tried the following, but nothing came out: +Я попробовал следующее, но ничего не вышло: ~~~ open("|less", "w").puts "abc" ~~~ -That's because the program ends immediately, and `less` never gets a chance -to see the stuff you've written to it, never mind to display it. -Make sure that the IO is properly closed and it will wait until `less` ends. +Это происходит потому, что программа немедленно завершается, и у `less` нет возможности увидеть то, что вы в него записали, не говоря уже о том, чтобы это отобразить. Убедитесь, что ввод-вывод (IO) должным образом закрыт, и программа будет ждать завершения `less`. ~~~ open("|less", "w") {|f| f.puts "abc" } ~~~ -### What happens to a `File` object which is no longer referenced? +### Что происходит с объектом `File`, на который больше нет ссылок? -A `File` object which is no longer referenced becomes eligible for garbage -collection. The file will be closed automatically when the `File` object is -garbage collected. +Объект `File`, на который больше нет ссылок, становится доступным для сборки мусора. Файл будет автоматически закрыт, когда объект `File` будет собран сборщиком мусора. -### I feel uneasy if I don't close a file. +### Я чувствую себя неспокойно, если не закрываю файл. -There are at least four good ways of ensuring that you do close a file: +Существует как минимум четыре хороших способа гарантировать закрытие файла: ~~~ # (1) @@ -193,24 +165,22 @@ File.foreach("file") {|line| print line } File.readlines("file").each {|line| print line } ~~~ -### How can I sort files by their modification time? +### Как я могу отсортировать файлы по времени их изменения? ~~~ Dir.glob("*").sort {|a, b| File.mtime(b) <=> File.mtime(a) } ~~~ -Although this works (returning a list in reverse chronological order) it -isn't very efficient, as it fetches the files' modification times from the -operating system on every comparison. +Хотя это работает (возвращая список в обратном хронологическом порядке), это не очень эффективно, так как при каждом сравнении время изменения файлов запрашивается у операционной системы. -More efficiency can be bought with some extra complexity: +Большей эффективности можно добиться с некоторой дополнительной сложностью: ~~~ Dir.glob("*").map {|f| [File.mtime(f), f] }. sort {|a, b| b[0] <=> a[0] }.map(&:last) ~~~ -### How can I count the frequency of words in a file? +### Как я могу подсчитать частоту слов в файле? ~~~ freq = Hash.new(0) @@ -218,7 +188,7 @@ File.read("example").scan(/\w+/) {|word| freq[word] += 1 } freq.keys.sort.each {|word| puts "#{word}: #{freq[word]}" } ~~~ -Produces: +Результат: ~~~ and: 1 @@ -230,13 +200,11 @@ three: 1 two: 1 ~~~ -### How can I sort strings in alphabetical order? +### Как я могу отсортировать строки в алфавитном порядке? -If you want your strings to sort 'AAA', 'BBB', ..., 'ZZZ', 'aaa', 'bbb', -then the built-in comparison will work just fine. +Если вы хотите, чтобы ваши строки сортировались как 'AAA', 'BBB', ..., 'ZZZ', 'aaa', 'bbb', тогда встроенное сравнение будет работать отлично. -If you want to sort ignoring case distinctions, compare downcased versions of -the strings in the sort block: +Если вы хотите сортировать, игнорируя различия в регистре, сравнивайте версии строк в нижнем регистре в блоке сортировки: ~~~ array = %w( z bB Bb bb Aa BB aA AA aa a A ) @@ -244,18 +212,17 @@ array.sort {|a, b| a.downcase <=> b.downcase } # => ["a", "A", "Aa", "aA", "AA", "aa", "bB", "Bb", "bb", "BB", "z"] ~~~ -If you want to sort so that the 'A's and 'a's come together, but 'a' is -considered greater than 'A' (so 'Aa' comes after 'AA' but before 'AB'), use: +Если вы хотите сортировать так, чтобы 'A' и 'a' шли вместе, но 'a' считалось больше, чем 'A' (так что 'Aa' идет после 'AA', но перед 'AB'), используйте: ~~~ array.sort {|a, b| (a.downcase <=> b.downcase).nonzero? || a <=> b } # => ["A", "a", "AA", "Aa", "aA", "aa", "BB", "Bb", "bB", "bb", "z"] ~~~ -### How can I expand tabs to spaces? +### Как я могу развернуть знаки табуляции в пробелы? {: #tab-expansion} -If `a` holds the string to be expanded, you could use one of: +Если `a` хранит строку, которую нужно развернуть, вы можете использовать один из вариантов: ~~~ 1 while a.sub!(/(^[^\t]*)\t(\t*)/){$1+" "*(8-$1.size%8+8*$2.size)} @@ -265,35 +232,23 @@ If `a` holds the string to be expanded, you could use one of: a.gsub!(/([^\t]{8})|([^\t]*)\t/n){[$+].pack("A8")} ~~~ -### How can I escape a backslash in a regular expression? +### Как я могу экранировать обратный слэш в регулярном выражении? -`Regexp.quote('\\')` escapes a backslash. +`Regexp.quote('\\')` экранирует обратный слэш. -It gets trickier if you are using `sub` and `gsub`. Say you write -`gsub(/\\/, '\\\\')`, hoping to replace each backslash with two. -The second argument is converted to `'\\'` in syntax analysis. When the -substitution occurs, the regular expression engine converts this to `'\'`, -so the net effect is to replace each single backslash with another single -backslash. You need to write `gsub(/\\/, '\\\\\\')`! +Ситуация усложняется, если вы используете `sub` и `gsub`. Допустим, вы пишете `gsub(/\\/, '\\\\')`, надеясь заменить каждый обратный слэш двумя. Второй аргумент преобразуется в `'\\'` при синтаксическом анализе. Когда происходит замена, движок регулярных выражений преобразует это в `'\'`, поэтому конечный эффект заключается в замене каждого одиночного обратного слэша другим одиночным обратным слэшем. Вам нужно написать `gsub(/\\/, '\\\\\\')`! -However, using the fact that `\&` contains the matched string, you could also -write `gsub(/\\/, '\&\&')`. +Однако, используя тот факт, что `\&` содержит совпавшую строку, вы также могли бы написать `gsub(/\\/, '\&\&')`. -If you use the block form of `gsub`, i.e. `gsub(/\\/) { '\\\\' }`, the string -for substitution is analyzed only once (during the syntax pass) and the -result is what you intended. +Если вы используете блочную форму `gsub`, то есть `gsub(/\\/) { '\\\\' }`, строка для замены анализируется только один раз (во время синтаксического прохода), и результат будет таким, как вы и задумывали. -### What is the difference between `sub` and `sub!`? +### В чем разница между `sub` и `sub!`? -In `sub`, a copy of the receiver is generated, substituted, and returned. +В `sub` создается копия получателя, в ней производится замена, и она возвращается. -In `sub!`, the receiver is altered and returned if any match was found. -Otherwise, `nil` is returned. +В `sub!` изменяется сам получатель, который и возвращается, если было найдено совпадение. В противном случае возвращается `nil`. -Methods like `sub!`, which alter the attribute of the receiver, -are called [destructive methods](../7/#destructive-method). -Usually, if there are two similar methods and one is destructive, -the destructive one has a suffix `!`. +Методы вроде `sub!`, которые изменяют атрибут получателя, называются [деструктивными методами](../7/#destructive-method). Обычно, если существуют два похожих метода и один из них деструктивный, у деструктивного есть суффикс `!`. ~~~ def foo(str) @@ -312,48 +267,40 @@ foo(obj) # => "baz" obj # => "baz" ~~~ -### Where does `\Z` match? +### Где совпадает `\Z`? -`\Z` matches just before the last `\n` (newline) if the string ends -with a `\n`, otherwise it matches at the end of a string. +`\Z` совпадает непосредственно перед последним `\n` (символом новой строки), если строка заканчивается на `\n`, в противном случае оно совпадает в конце строки. -### What is the difference between `thread` and `fork`? +### В чем разница между `thread` и `fork`? {% include warnings/faq-out-of-date.html %} -Ruby threads are implemented within the interpreter, while `fork` invokes the -operating system to create a separately executing subprocess. +Потоки Ruby (threads) реализованы внутри интерпретатора, в то время как `fork` обращается к операционной системе для создания отдельно выполняемого подпроцесса. -Thread and fork have the following characteristics: +Потоки и форки имеют следующие характеристики: -* `fork` is slow, `thread` is not. -* `fork` does not share the memory space. -* `thread` does not cause thrashing. -* `thread` works on DOS. -* When `thread` gets in a deadlock, the whole process stops. -* `fork` can take advantage of pauses waiting for I/O to complete, - `thread` does not (at least not without some help). +* `fork` работает медленно, `thread` — нет. +* `fork` не разделяет пространство памяти. +* `thread` не вызывает «пробуксовки» (thrashing). +* `thread` работает под DOS. +* Когда `thread` попадает в состояние взаимной блокировки (deadlock), останавливается весь процесс. +* `fork` может использовать паузы при ожидании завершения ввода-вывода, `thread` — нет (по крайней мере, не без некоторой помощи). -You probably shouldn't mix `fork` and `thread`. +Вам, вероятно, не стоит смешивать `fork` и `thread`. -### How can I use `Marshal`? +### Как я могу использовать `Marshal`? -`Marshal` is used to store an object in a file or a string, and later -reconstitute it. Objects may be stored using: +`Marshal` используется для сохранения объекта в файл или строку и его последующего восстановления. Объекты можно сохранять с помощью: ~~~ Marshal.dump( obj [, io ] [, lev] ) ~~~ -`io` is a writable `IO` object, `lev` designates the level to which objects -are dereferred and stored. If `lev` levels of dereferring are done and object -references still exist, then `dump` stores just the reference, not the object -referenced. This is not good, as these referenced objects cannot be -subsequently reconstructed. +`io` — это объект `IO`, доступный для записи, `lev` указывает уровень, до которого объекты разыменовываются и сохраняются. Если выполнено `lev` уровней разыменования, а ссылки на объекты все еще существуют, то `dump` сохраняет только ссылку, а не сам объект, на который она указывает. Это плохо, так как такие объекты не могут быть впоследствии восстановлены. -If `io` is omitted, the marshaled objects are returned in a string. +Если `io` опущено, маршалированные объекты возвращаются в виде строки. -You can load objects back using: +Вы можете загрузить объекты обратно, используя: ~~~ obj = Marshal.load(io) @@ -361,11 +308,11 @@ obj = Marshal.load(io) obj = Marshal.load(str) ~~~ -where `io` is a readable `IO` object, `str` is the dumped string. +где `io` — это объект `IO`, доступный для чтения, `str` — это дамп строки. -### How can I use `trap`? +### Как я могу использовать `trap`? -`trap` associates code blocks with external events (signals). +`trap` связывает блоки кода с внешними событиями (сигналами). ~~~ trap("PIPE") { raise "SIGPIPE" } diff --git a/ru/documentation/faq/index.md b/ru/documentation/faq/index.md index 91c978b8f7..b8899e9d9d 100644 --- a/ru/documentation/faq/index.md +++ b/ru/documentation/faq/index.md @@ -1,62 +1,62 @@ --- layout: page -title: "Official Ruby FAQ" +title: "Официальный FAQ по Ruby" lang: ru header: |
- Content + Оглавление | - 1 + 1 | - 2 + 2 | - 3 + 3 | - 4 + 4 | - 5 + 5 | - 6 + 6 | - 7 + 7 | - 8 + 8 | - 9 + 9 | - 10 + 10 | - 11 + 11
-

Official Ruby FAQ

+

Официальный FAQ по Ruby

--- -This document contains Frequently Asked Questions about Ruby with answers. +В этом документе собраны Часто Задаваемые Вопросы о Ruby с ответами. {: .summary} -This FAQ is based on "[The Ruby Language FAQ][original-faq]" originally -compiled by Shugo Maeda and translated into English by Kentaro Goto. -Thanks to Zachary Scott and Marcus Stollsteimer for incorporating -the FAQ into the site and for a major overhaul of the content. +Этот FAQ основан на "[The Ruby Language FAQ][original-faq]", который изначально +составил Shugo Maeda и перевел на английский Kentaro Goto. +Спасибо Zachary Scott и Marcus Stollsteimer за внедрение +этого FAQ на сайт и серьезную переработку контента. -The code examples in this document have been run using Ruby 2.3. +Примеры кода в этом документе были выполнены с использованием Ruby 2.3. [original-faq]: http://ruby-doc.org/docs/ruby-doc-bundle/FAQ/FAQ.html {% include faq-notice.md %} -## Content - -* [General questions](1/) -* [How does Ruby stack up against...?](2/) -* [Installing Ruby](3/) -* [Variables, constants, and arguments](4/) -* [Iterators](5/) -* [Syntax](6/) -* [Methods](7/) -* [Classes and modules](8/) -* [Built-in libraries](9/) -* [Extension library](10/) -* [Other features](11/) +## Оглавление + +* [Общие вопросы](1/) +* [Как Ruby выглядит на фоне...?](2/) +* [Установка Ruby](3/) +* [Переменные, константы и аргументы](4/) +* [Итераторы](5/) +* [Синтаксис](6/) +* [Методы](7/) +* [Классы и модули](8/) +* [Встроенные библиотеки](9/) +* [Библиотека расширений](10/) +* [Другие возможности](11/)