2

讓我們假設我有一個非常簡單的Ruby程序:如何在Ruby調試器(ruby-debug/rdebug)中設置變量?

require 'rubygems' 
require 'ruby-debug' 
x = 1 
debugger 
puts x 

當執行到「調試器」命令,它正確地停止和給我的「RDB」提示。

現在:我的目標是讓程序打印2而不是1.如何做到這一點?如果鍵入 '幫助',然後中,RDebug告訴我:

ruby-debug help v0.10.4 
Type 'help <command-name>' for help on a specific command 

Available commands: 
backtrace delete enable help method putl  set  trace  
break  disable eval info next quit  show undisplay 
catch  display exit irb p  reload step up  
condition down  finish kill pp  restart thread var  
continue edit  frame list ps  save  tmate where 

的 '設置' 命令看起來很有希望......但是:

(rdb:1) help set 
Modifies parts of the ruby-debug environment. Boolean values take 
on, off, 1 or 0. 
You can see these environment settings with the "show" command. 

-- 
List of set subcommands: 
-- 
set annotate -- Set annotation level 
set args -- Set argument list to give program being debugged when it is started 
set autoeval -- Evaluate every unrecognized command 
set autolist -- Execute 'list' command on every breakpoint 
set autoirb -- Invoke IRB on every stop 
set autoreload -- Reload source code when changed 
set basename -- Report file basename only showing file names 
set callstyle -- Set how you want call parameters displayed 
set debuggertesting -- Used when testing the debugger 
set forcestep -- Make sure 'next/step' commands always move to a new line 
set fullpath -- Display full file names in frames 
set history -- Generic command for setting command history parameters 
set keep-frame-bindings -- Save frame binding on each call 
set linetrace+ -- Set line execution tracing to show different lines 
set linetrace -- Set line execution tracing 
set listsize -- Set number of source lines to list by default 
set trace -- Display stack trace when 'eval' raises exception 
set width -- Number of characters the debugger thinks are in a line  

沒有骰子。該怎麼辦?

我看着Official ruby-debug doc,我看着RailsGuides Debugging Rails Applications doc,但沒有看到答案。

回答

2

您需要使用evalp,然後使用finish繼續執行腳本。喜歡的東西:

(rdb:1) p x=2 
2 
(rdb:1) finish 
2 
+0

哇,聰明。 p命令打印表達式,'x = 2'是一個表達式,因此將2賦值給變量x成爲p命令的副作用。 – Purplejacket 2011-01-13 22:23:10

2
→ ruby temp.rb 
temp.rb:5 
puts x 
(rdb:1) irb 
ruby-1.9.2-p0 > x 
=> 1 
ruby-1.9.2-p0 > x = 2 
=> 2 
ruby-1.9.2-p0 > ^D 
temp.rb:5 
puts x 
(rdb:1) cont 
2 
4

兩個邁克和noodi的答案是偉大的!請注意,儘管Mike的示例中的「finish」會在方法或塊的末尾(這裏實際上是程序的結束),而noodi的解決方案中的「continue」會繼續執行。

另請注意,如果「set autoeval」設置爲「on」,則在(rdb)提示符處鍵入的任何內容都不會自動執行。因此,您不需要鍵入「p x = 1」,而是可以輸入「x = 1」,而不必進入irb以避免「p」或「eval」。

在較新的打孔系列調試器中,https://github.com/rocky/rb-trepanning/wikihttps://github.com/rocky/rbx-trepanning/wiki默認情況下設置爲打開。