Programming Ruby 1.9 (3rd edition): The Pragmatic Programmers' Guide / Программирование на Ruby 1.9 (3-е издание): Руководство прагматичного программиста

→Finally, this code illustrates a simple piece of validation. The Float method takes its argument and converts it to a floating-point number,1 terminating the program with an error if that conversion fails. (Later in the book we'll see how to handle these exceptional situations.) What we're doing here is saying that we want to accept any object for the price parameter as long as that parameter can be converted to a float. We can pass in a float, an integer, and even a string containing the representation of a float, and it will work. Let's try this now. We'll create three objects, each with different initial state. The p method prints out an internal representation of an object. Using it, we can see that in each case our parameters got transferred into the object's state, ending up as instance variables:
0 И конечно этот код демонстрирует простой пример валидации.
Метод Float берет свой аргумент и конвертирует его в число с плавающей точкой, 1 терминирует программу вместе с ошибкой если перенос данных проваливается.(Позже в этой книге мы рассмотрим то как контролировать эти ситуации.) Здесь мы говорим что нам нужно допустить любой объект для параметра цены на столько долго на сколько параметр может конвертироваться в float. Мы можем передать в float целое число и он будет работать.
→Why did we use p to write out our objects, rather than puts? Well, let's repeat the code using puts:
0 Почему мы используем p чтобы напечать наши объекты в отличии от puts? Давайте используем puts для повторения кода:
→# # #
0 # # #
→produces:
0 Выводит:
→p b3
0 p b3
→b3 = BookInStock.new("isbn3", "5.67")
0 b3 = BookInStock.new("isbn3", "5.67")
→p b2
0 <code> p b2</code>
→b2 = BookInStock.new("isbn2", 3.14)
0 <code>b2 = BookInStock.new("isbn2", 3.14)</code>
→p b1
0 <code>p b1</code>
→b1 = BookInStock.new("isbn1", 3)
0 <code>b1 = BookInStock.new("isbn1", 3) </code>
→def initialize(isbn, price) ©isbn = isbn ©price = Float(price) end end
0 <code>def initialize(isbn, price) ©isbn = isbn ©price = Float(price) end end </code>
→class BooklnStock
0 <code>class BooklnStock</code>
→Download samples/tutclasses_5.rb
0 <code>Download samples/tutclasses_5.rb</code>
→This method also illustrates something that often trips up newcomers to Ruby. Notice how we say @isbn = isbn. It's easy to imagine that the two variables here, @isbn and isbn, are somehow related—it looks like they have the same name. But they don't. The former is an instance variable, and the "at" sign is actually part of its name.
−1 Этот метод также иллюстрирует то, что часто поездки новичков в Ruby. Обратите внимание, как мы говорим @ = ISBN ISBN. Это легко представить что мы имеем здесь две переменные @isbn и isbn, и они как-то отличаются-кажется что у них одинаковые имена. Но это не так. <i>former</i> это экземпляр переменной и "at" является частью этого имени
→For class BooklnStock, the initialize method takes two parameters. These parameters act just like local variables within the method, so they follow the local variable naming convention of starting with a lowercase letter. But, as local variables, they would just evaporate once the initialize method returns, so we need to transfer them into instance variables. This is very common behavior in an initialize method—the intent is to have our object set up and usable by the time initialize returns.
0 Для класса BooklnStock метод initialize берет два параметра. Эти два параметра работают также как локальные переменные с методом и так они выполняют локальную переменную именуемую конвенцией и начинающеюся с маленькой буквы. Но локальные переменные просто исчезают после инициализации метод возвращает значение, поэтому мы должны передавать их в переменных экземпляра. Это обычное поведение при инициализации метода, наша цель это настроить этот объект чтобы его можно было использовать во время возврата при инициализации.
→initialize is a special method in Ruby programs. When you call BooklnStock.new to create a new object, Ruby allocates some memory to hold an uninitialized object and then calls that object's initialize method, passing in any parameters that were passed to new. This gives you a chance to write code that sets up your object's state.
0 <i>initialize</i> это специальный метод в программах Ruby. Когда вы вызываете BooklnStock.new для создания нового объекта, Ruby выделяет какое то количество памяти для содержания не инициализированного объекта и вызывает метод <i>initialize</i> передавая любые параметры которые мы передали <i>new</i>. Это дает вам возможность написать код который определяет состояние объекта.
→def initialize(isbn, price) ©isbn = isbn ©price = Float(price) end end
0 <code>def initialize(isbn, price) ©isbn = isbn ©price = Float(price) end end</code>
→class BooklnStock
0 <code>class BooklnStock </code>
→Download samples/tutclasses_4.rb
0 <p style="font-family: times, serif; font-size:10pt; font-style:italic">Download samples/tutclasses_4.rb</p>
→So, here's our updated class definition:
0 И так здесь наше обновленное определение класса:
Резюме
Пол:
мужчина
Родной язык:
русский
С нами:
с 19 сентября 2010 г. (5874 дня)
Не является членом клуба.
Деятельность:
249 версий перевода с общим рейтингом 9
5 комментариев
Карма: 3 (оценок: 3)
Написать Droidos личное сообщение