Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Ruby / Yukihiro Matsumoto_Programming Ruby.doc
Скачиваний:
121
Добавлен:
06.06.2015
Размер:
2.71 Mб
Скачать

But It Doesn't Work!

So you've read through enough of the book, you start to write your very own Ruby program, and it doesn't work. Here's a list of common gotchas and other tips.

  • Attribute setter not being called. Within an object, Ruby will parse setter=as an assignment to a local variable, not as a method call. Useself.setter=to indicate the method call.

  • A parse error at the last line of the source often indicates a missing endkeyword.

  • Make sure that the type of the object you are using is what you think it is. If in doubt, use Object#type to check the type of an object.

  • Make sure that your methods start with a lowercase letter and that classes and constants start with an uppercase letter.

  • If you happen to forget a ``,'' in an argument list---especially to print---you can produce some very odd error messages.

  • Block parameters are actually local variables. If an existing local 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.

  • Watch out for precedence, especially when using {}instead ofdo/end.

  • Make sure that the open parenthesis of a method's parameter list butts up against the end of the method name with no intervening spaces.

  • Output written to a terminal may be buffered. This means that you may not see a message you write immediately. In addition, if you write messages to both $stdoutand$stderr, the output may not appear in the order you were expecting. Always use nonbuffered I/O (setsync=true) for debug messages.

  • If numbers don't come out right, perhaps they're strings. Text read from a file will be a String, and will not be automatically converted to a number by Ruby. A call toto_iwill work wonders. A common mistake Perl programmers make is:

    while gets

      num1, num2 = split /,/

      # ...

    end

  • Unintended aliasing---if you are using an object as the key of a hash, make sure it doesn't change its hash value (or arrange to call Hash#rehash if it does).

  • Use trace_varto watch when a variable changes value.

  • Use the debugger.

  • Use Object#freeze . If you suspect that some unknown portion of code is setting a variable to a bogus value, try freezing the variable. The culprit will then be caught during the attempt to modify the variable.

There's one major technique that makes writing Ruby code both easier and more fun. Develop your applications incrementally.Write a few lines of code, then run them. Write a few more, then run those. One of the major benefits of an untyped language is that things don't have to be complete before you use them.

But It's Too Slow!

Ruby is an interpreted, high-level language, and as such it may not perform as fast as a lower-level language such as C. In this section, we'll list some basic things you can do to improve performance; also have a look in the index under Performancefor other pointers.

Create Locals Outside Blocks

Try defining the variables used in a block before the block executes. When iterating over a very large set of elements, you can improve execution speed somewhat by predeclaring any iterator variables. In the first example below, Ruby has to create new xandyvariables on each iteration, but in the second version it doesn't. We'll use thebenchmarkpackage from the Ruby Application Archive to compare the loops:

require "benchmark"

include Benchmark

n = 1000000

bm(12) do |test|

  test.report("normal:")    do

    n.times do |x|

      y = x + 1

    end

  end

  test.report("predefine:") do

    x = y = 0

    n.times do |x|

      y = x + 1

    end

  end

end

produces:

                  user     system      total        real

normal:       2.490000   0.000000   2.490000 (  2.462660)

predefine:    2.190000   0.010000   2.200000 (  2.196071)

Соседние файлы в папке Ruby