说我有:
begin
2.times do
a = 1
1/0
end
rescue
puts $!
debugger
end
在此示例中,我想获得a
的值。如果在a
块中初始化begin
,那么我可以在救援时访问它。但是,在此示例中,a
是块本地的。当我解救时,有没有办法在异常时获得绑定?
答案 0 :(得分:1)
你不能只在begin
区块内放置另一个rescue
,do
块吗?
答案 1 :(得分:0)
似乎有可能做到这一点。但这不是很好:
class Foo < Exception
attr_reader :call_binding
def initialize
# Find the calling location
expected_file, expected_line = caller(1).first.split(':')[0,2]
expected_line = expected_line.to_i
return_count = 5 # If we see more than 5 returns, stop tracing
# Start tracing until we see our caller.
set_trace_func(proc do |event, file, line, id, binding, kls|
if file == expected_file && line == expected_line
# Found it: Save the binding and stop tracing
@call_binding = binding
set_trace_func(nil)
end
if event == :return
# Seen too many returns, give up. :-(
set_trace_func(nil) if (return_count -= 1) <= 0
end
end)
end
end
class Hello
def a
x = 10
y = 20
raise Foo
end
end
class World
def b
Hello.new.a
end
end
begin World.new.b
rescue Foo => e
b = e.call_binding
puts eval("local_variables.collect {|l| [l, eval(l)]}", b).inspect
end
来源:How can I get source and variable values in ruby tracebacks?