aist: переводы
Programming Ruby 1.9 (3rd edition): The Pragmatic Programmers' Guide / Программирование на Ruby 1.9 (3-е издание): Руководство прагматичного программиста
→produces:
0 выдаёт:
→produces:
1 выдаёт:
→The code in the block (puts "In the block") is executed twice, once for each call to yield.
1 Код в блоке (puts "In the block") выполняется дважды, по разу для каждого вызова yield.
→Here we ask an array to call the block once for each of its elements. Then, object 5 calls a block five times. Rather than use for loops, in Ruby we can ask the number 3 to call a block, passing in successive values until it reaches 6. Finally, the range of characters from a to e invokes a block using the method each.
1 Здесь мы вызываем блок для каждого элемента массива. Вот объект 5 вызывает блок 5 раз. Вместо использования циклов, в Ruby мы запрашиваем цифру 3 вызывать блок до тех пор, пока она не достигнет 6. И, наконец, для набора символов от а до е блок вызывается с использованием метода each.
→Many of the looping constructs that are built into languages such as C and Java are simply method calls in Ruby, with the methods invoking the associated block zero or more times:
1 Многие из циклических конструкций, встроенных в языки типа С и Java, в Ruby реализованы в виде обычных вызовов методов, которые применяют связанный блок ноль или более раз:
→produces:
0 выдаёт:
→Code blocks are used throughout the Ruby library to implement iterators, which are methods that return successive elements from some kind of collection, such as an array:
1 Блоки кода используются посредством библиотеки Ruby для внедрения итераторов, которые являются методами, возвращающими соответствующие элементы из некоего набора данных, например, массива:
→cat dog horse *****3456abcde
1 <font face="verdana">
<table><tbody><tr><td>cat</td><td>dog</td><td>horse</td><td> </td><td> </td></tr><tr><td>*</td><td>*</td><td>*</td><td>*</td><td>*</td></tr><tr><td>3</td><td>4</td><td>5</td><td>6</td><td> </td></tr><tr><td>a</td><td>b</td><td>c</td><td>d</td><td>e</td></tr></tbody></table></font>
<table><tbody><tr><td>cat</td><td>dog</td><td>horse</td><td> </td><td> </td></tr><tr><td>*</td><td>*</td><td>*</td><td>*</td><td>*</td></tr><tr><td>3</td><td>4</td><td>5</td><td>6</td><td> </td></tr><tr><td>a</td><td>b</td><td>c</td><td>d</td><td>e</td></tr></tbody></table></font>
→print line
1 print line
→line = gets
1 line = gets
→You have many ways to read input into your program. Probably the most traditional is to use the routine gets, which returns the next line from your program’s standard input stream:
0 Вы можете считывать входящие данные в свою программу многими способами. Возможно самый традиционный - использовать подпрограмму gets, которая выдаёт данные из входящего потока вашей программы построчно:
→In this example, the format string "Number: %5.2f,\nString: %s\n" tells printf to substitute in a floating-point number (with a minimum of five characters, two after the decimal point) and a string. Notice the newlines (\n) embedded in the string; each moves the output onto the next line.
1 В данном примере строка формата "Number: %5.2f,\nString: %s\n" говорит printf представить число с плавающей точкой (минимум 5 символов, с двумя после запятой) и строку. Заметьте, что переводы строки (\n) вписаны в строку, после каждого аргумента строка переводится.
→Ruby comes with a comprehensive I/O library. However, in most of the examples in this book, we’ll stick to a few simple methods. We’ve already come across two methods that do output: puts writes its arguments with a newline after each; print also writes its arguments but with no newline. Both can be used to write to any I/O object, but by default they write to standard output.
1 Ruby имеет полноценную библиотеку ввода-вывода. Однако, в большинстве примеров в этой книге, мы будем опираться на несколько простых методов. Мы уже применяли два метода, которые выводят информацию: puts пишет каждый аргумент с переводом строки после него; print также пишет аргументы, но без перевода строки. Оба могут писать в любой объект ввода-вывода, но по умолчанию пишут в стандартный вывод.
→Reading and ’Riting
1 <b>Чтение и Запись</b>
→Because gets returns nil when it reaches the end of input, you can use its return value in a loop condition. Notice that here the condition to the while is an assignment: we store whatever gets returns into the variable line and then test to see whether that returned value was nil or false before continuing:
1 Так как gets возвращает nil при достижении конца входящих данных, вы можете использовать его в циклах с условием. Учтите, что в While условие является присвоением: мы помещаем выходные данные Gets в переменную line, а потом, перед тем как продолжить, проверяем выходное значение на nil или false:
→Another output method we use a lot is printf, which prints its arguments under the control of a format string (just like printf in C or Perl):
1 Другой метод, который мы часто используем это printf, который выводит переданные ему аргументы согласно строке формата (примерно как в С или Perl):
→produces:
1 выдаёт:
→printf("Number: %5.2f,\nString: %s\n", 1.23, "hello")
1 printf("Number: %5.2f,\nString: %s\n", 1.23, "hello")
→Often, the arguments to a program are the names of files that you want to process. In this case, you can use a second technique: the variable ARGF is a special kind of I/O object that acts like all the contents of all the files whose names are passed on the command line (or standard input if you don’t pass any filenames). We’ll look at that some more on page 342.
1 Часто параметрами программы являются имена файлов, которые вы хотите обработать. В этом случае можно использовать второй путь: переменную ARGF - специальный тип объекта ввода-вывода, который действует как содержимое всех перечисленных в командной строке файлов (или в стандартном вводе, если ничего не перечислено). Мы рассмотрим это дальше на стр. 342.
→That’s it. We’ve finished our lightning-fast tour of some of the basic features of Ruby. We took a look at objects, methods, strings, containers, and regular expressions; saw some simple control structures; and looked at some rather nifty iterators. We hope this chapter has given you enough ammunition to be able to attack the rest of this book. Time to move on and move up—up to a higher level. Next, we’ll be looking at classes and objects, things that are at the same time both the highest-level constructs in Ruby and the essential underpinnings of the entire language.
2 Вот и подошел к концу наш молниеносный тур по некоторым базовым возможностям Ruby. Мы рассмотрели объекты, методы, строки, контейнеры и регулярные выражения; некоторые простые управляющие структуры; некоторые довольно изящные итераторы. Надеемся, что этт раздел предоставил вам достаточно патронов, чтобы расправиться с оставшейся частью этой книги. Время двигаться вперед и вверх - к более высокому уровню. Далее мы рассмотрим классы и объекты - вещи, которые одновременно являются конструкциями высшего уровня в Ruby и существенными основами всего языка.
Резюме
- Пол:
- мужчина
- Родной язык:
- русский
- С нами:
- с 14 февраля 2009 г. (6455 дней)
- Деятельность:
-
34845 версий перевода
с общим рейтингом 2579
805 комментариев
Карма: 91 (оценок: 197)
