gpt4 book ai didi

ruby - 我如何跟踪我的堆栈跟踪高度以进行调试?

转载 作者:数据小太阳 更新时间:2023-10-29 07:55:46 25 4
gpt4 key购买 nike

我希望我的代码执行以下操作:

def debug (message)
puts message.rjust(message.length + (stack_trace-1 * 2)) # -1 for the call to debug
end

def a
debug "in a"
b
debug "end a"
end

def b
debug "in b"
c
debug "end b"
end

def c
debug "in c"
meaningful_work
debug "end c"
end

输出:

in a
in b
in c
end c
end b
end a

我以前用 PHP 做过,像这样:

function echon($string){
$nest_level = count(debug_backtrace()) - 1; // minus one to ignore the call to *this* function
echo str_repeat(" ", $nest_level) . $string . "\n";
}

据我的 google-fu 所知,没有与 debug_backtrace 等效的 Ruby。我不想修改我正在使用的代码库中的所有众多方法的调用以传递回溯 - 这是不必要的麻烦且难以恢复。

有没有我可以用来跟踪这里的全局变量?

最佳答案

只需使用 Kernel#caller使用 .lengthcaller(0).length 将为您提供当前堆栈深度。

例子:

irb(main):001:0> caller(0)
=> ["(irb):1:in `irb_binding'", "/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/irb/workspace.rb:86:in `eval'", "/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/irb/workspace.rb:86:in `evaluate'", "/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/irb/context.rb:380:in `evaluate'", "/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/irb.rb:492:in `block (2 levels) in eval_input'", "/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/irb.rb:624:in `signal_status'", "/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/irb.rb:489:in `block in eval_input'", "/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/irb/ruby-lex.rb:247:in `block (2 levels) in each_top_level_statement'", "/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/irb/ruby-lex.rb:233:in `loop'", "/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/irb/ruby-lex.rb:233:in `block in each_top_level_statement'", "/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/irb/ruby-lex.rb:232:in `catch'", "/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/irb/ruby-lex.rb:232:in `each_top_level_statement'", "/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/irb.rb:488:in `eval_input'", "/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/irb.rb:397:in `block in start'", "/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/irb.rb:396:in `catch'", "/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/irb.rb:396:in `start'", "/usr/bin/irb:12:in `<main>'"]
irb(main):002:0> caller(0).length
=> 17

关于ruby - 我如何跟踪我的堆栈跟踪高度以进行调试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27491007/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com