When Trouble Strikes

优质
小牛编辑
143浏览
2023-12-01

Sad to say, it is possible to write buggy programs using Ruby. Sorry about that.
But not to worry! Ruby has several features that will help debug your programs. We'll look at these features, and then we'll show some common mistakes you can make in Ruby and how to fix them.

Ruby Debugger


Ruby comes with a debugger, which is conveniently built into the base system. You can run the debugger by invoking the interpreter with the-r debug option, along with any other Ruby options and the name of your script:

ruby -r debug [
options
] [
programfile
] [
arguments
]

The debugger supports the usual range of features you'd expect, including the ability to set breakpoints, to step into and step over method calls, and to display stack frames and variables.
It can also list the instance methods defined for a particular object or class, and allows you to list and control separate threads within Ruby. Table 12.1 on page 131 lists all of the commands that are available under the debugger.
If your Ruby hasreadline support enabled, you can use cursor keys to move back and forth in command history and use line editing commands to amend previous input.
To give you an idea of what the Ruby debugger is like, here is a sample session.

% 
ruby -rdebug t.rb

Debug.rb
Emacs support available.
t.rb:1:def fact(n)
(rdb:1)
list 1-9

[1, 10] in t.rb
=> 1 def fact(n)
2 if n <= 0
3 1
4 else
5 n * fact(n-1)
6 end
7 end
8
9 p fact(5)
(rdb:1)
b 2

Set breakpoint 1 at t.rb:2
(rdb:1)
c

breakpoint 1, fact at t.rb:2
t.rb:2: if n <= 0
(rdb:1)
disp n

1: n = 5
(rdb:1)
del 1

(rdb:1)
watch n==1

Set watchpoint 2
(rdb:1)
c

watchpoint 2, fact at t.rb:fact
t.rb:1:def fact(n)
1: n = 1
(rdb:1)
where

--> #1 t.rb:1:in `fact'
#2 t.rb:5:in `fact'
#3 t.rb:5:in `fact'
#4 t.rb:5:in `fact'
#5 t.rb:5:in `fact'
#6 t.rb:9
(rdb:1)
del 2

(rdb:1)
c

120

Interactive Ruby


If you want to play with Ruby, there is a facility called Interactive Ruby---irb, for short. irb is essentially a Ruby ``shell'' similar in concept to an operating system shell (complete with job control). It provides an environment where you can ``play around'' with the language in real time. You launch irb at the command prompt:

irb [
irb-options
] [
ruby_script
] [
options
]

irb will display the value of each expression as you complete it. For instance:

% irb
irb(main):001:0>
a = 1 +

irb(main):002:0*
2 * 3 /

irb(main):003:0*
4 % 5

2
irb(main):004:0>
2+2

4
irb(main):005:0>
def test

irb(main):006:1>
puts "Hello, world!"

irb(main):007:1>
end

nil
irb(main):008:0>
test

Hello, world!
nil
irb(main):009:0>

irb also allows you to create subsessions, each one of which may have its own context. For example, you can create a subsession with the same (top-level) context as the original session, or create a subsession in the context of a particular class or instance. The sample session shown in Figure 12.1 on page 126 is a bit longer, but shows how you can create subsessions and switch between them.

Figure not available...
For a full description of all the commands that irb supports, see the reference beginning on page 517.
As with the debugger, if your version of Ruby was built with GNU Readline support, you can use arrow keys (as with Emacs) or vi-style key bindings to edit individual lines or to go back and reexecute or edit a previous line---just like a command shell.
irb is a great learning tool: it's very handy if you want to try out an idea quickly and see if it works.

Editor Support


Ruby is designed to read a program in one pass; this means you can pipe an entire program to Ruby's standard input and it will work just fine.
We can take advantage of this feature to run Ruby code from inside an editor. In Emacs, for instance, you can select a region of Ruby text and use the commandMeta-| to execute Ruby. The Ruby interpreter will use the selected region as standard input and output will go to a buffer named ``*Shell Command Output*.'' This feature has come in quite handy for us while writing this book---just select a few lines of Ruby in the middle of a paragraph and try it out!
You can do something similar in the vi editor using ``:!ruby'' whichreplaces the program text with its output, or ``:w!ruby'', which displays the output without affecting the buffer. Other editors have similar features.
While we are on the subject, this would probably be a good place to mention that there is a Ruby mode for Emacs included in the distribution asmisc/ruby-mode.el. There are also several syntax-highlighting modules for vim (an enhanced version of the vi editor), jed, and other editors available on the net as well. Check the Ruby FAQ for current locations and availability.

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 parsesetter= 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 missingend keyword.

  • Make sure that the type of the object you are using is what you think it is. If in doubt, useObject#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$stdout and$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 aString, and will not be automatically converted to a number by Ruby. A call toto_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 callHash#rehash if it does).

  • Usetrace_var to watch when a variable changes value.

  • Use the debugger.

  • UseObject#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 underPerformance for 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 newx andy variables on each iteration, but in the second version it doesn't. We'll use thebenchmark package 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.450000 0.020000 2.470000 ( 2.468109)
predefine: 2.140000 0.020000 2.160000 ( 2.155307)

Use the Profiler


Ruby comes with a code profiler (documentation begins on on page 454). In and of itself, that isn't too surprising, but when you realize that the profiler is written in just about 50 lines of Ruby, that makes for a pretty impressive language.
You can add profiling to your code using the command-line option-rprofile, or from within the code usingrequire "profile". For example:

require "profile"
class Peter
def initialize(amt)
@value = amt
end

def rob(amt)
@value -= amt
amt
end
end

class Paul
def initialize
@value = 0
end

def pay(amt)
@value += amt
amt
end
end

peter = Peter.new(1000)
paul = Paul.new
1000.times do
paul.pay(peter.rob(10))
end

Run this, and you'll get something like the following.

 time   seconds   seconds    calls  ms/call  ms/call  name
32.14 0.27 0.27 1 270.00 840.00 Fixnum#times
30.95 0.53 0.26 1000 0.26 0.27 Paul#pay
29.76 0.78 0.25 1000 0.25 0.30 Peter#rob
5.95 0.83 0.05 1000 0.05 0.05 Fixnum#-
1.19 0.84 0.01 1000 0.01 0.01 Fixnum#+
0.00 0.84 0.00 1 0.00 0.00 Paul#initialize
0.00 0.84 0.00 2 0.00 0.00 Class#inherited
0.00 0.84 0.00 4 0.00 0.00 Module#method_added
0.00 0.84 0.00 1 0.00 0.00 Peter#initialize
0.00 0.84 0.00 1 0.00 840.00 #toplevel
0.00 0.84 0.00 2 0.00 0.00 Class#new
With the profiler, you can quickly identify and fix bottlenecks. Remember to check the code without the profiler afterward, though---sometimes the slowdown the profiler introduces can mask other problems.
Ruby is a wonderfully transparent and expressive language, but it does not relieve the programmer of the need to apply common sense: creating unnecessary objects, performing unneeded work, and creating generally bloated code are wasteful in any language.
Debugger commands
b[reak] [file:]line
Set breakpoint at given line infile (default current file).
b[reak] [file:]name
Set breakpoint atmethod infile.
b[reak]
Display breakpoints and watchpoints.
wat[ch] expr
Break when expression becomes true.
del[ete] [nnn]
Delete breakpointnnn (default all).
disp[lay] expr
Display value ofnnn every time debugger gets control.
disp[lay]
Show current displays.
undisp[lay] [nnn]
Remove display (default all).
c[ont]
Continue execution.
s[tep] nnn=1
Execute nextnnn lines, stepping into methods.
n[ext] nnn=1
Execute nextnnn lines, stepping over methods.
fi[nish]
Finish execution of the current function.
q[uit]
Exit the debugger.
w[here]
Display current stack frame.
f[rame]
Synonym forwhere.
l[ist] [start--end]
List source lines from start to end.
up nnn=1
Move upnnn levels in the stack frame.
down nnn=1
Move downnnn levels in the stack frame.
v[ar] g[lobal]
Display global variables.
v[ar] l[ocal]
Display local variables.
v[ar] i[stance]obj
Display instance variables ofobj.
v[ar] c[onst] Name
Display constants in class or module name.
m[ethod] i[nstance]obj
Display instance methods ofobj.
m[ethod] Name
Display instance methods of the class or module name.
th[read] l[ist]
List all threads.
th[read] [c[ur[rent]]]
Display status of current thread.
th[read] [c[ur[rent]]] nnn
Make threadnnn current and stop it.
th[read] stop nnn
Make threadnnn current and stop it.
th[read] resume nnn
Resume threadnnn.
[p] expr
Evaluateexpr in the current context.expr may include assignment to variables and method invocations.
empty
A null command repeats the last command.