|
 |
|
|
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. Use self.setter= to indicate the method call.
- A parse error
at the last line of the source often
indicates a missing
end keyword.
- 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 of do /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
$stdout and $stderr , the output may
not appear in the order you were expecting. Always use nonbuffered
I/O (set sync=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 to to_i
will 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_var to 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.
|
|
|