ruby断点函数的实现
我正在实现一个断点函数,用于在ruby中调试代码 我的断点函数与下面代码中的断点类似ruby断点函数的实现,ruby,debugging,breakpoints,callstack,Ruby,Debugging,Breakpoints,Callstack,我正在实现一个断点函数,用于在ruby中调试代码 我的断点函数与下面代码中的断点类似 def breakpoint s color_s = "\033[1m\033[33m" color_f = "\033[0m\033[22m" line= (caller.first.split ":")[1] puts "#{color_s}#{Time.new.strftime("%H:%M:%S")} line:#{line} -- #{s.to_s}#{color_
def breakpoint s
color_s = "\033[1m\033[33m"
color_f = "\033[0m\033[22m"
line= (caller.first.split ":")[1]
puts "#{color_s}#{Time.new.strftime("%H:%M:%S")} line:#{line} -- #{s.to_s}#{color_f}"
gets
end
a = 3
puts "Hello World"
breakpoint "test"
它将产生像这样的产出
Hello World
19:21:33 line:11 -- test
注意:line:11
是调用函数的行号
我的问题是如何从程序堆栈中获取变量名和值。例如,在上面的代码中:
a=3
您需要传递当前环境的binding
对象来打印局部变量
def breakpoint s, b
b.instance_eval{local_variables.each{|sym| puts "#{sym} = #{eval(sym.to_s)}"}}
...
end
a = 3
breakpoint "test", binding
我修改了sawa的回答:
def breakpoint s,a
color_s = "\033[1m\033[33m"
color_f = "\033[0m\033[22m"
line= (caller.first.split ":")[1]
vars = eval('local_variables',a).map{|v| "#{v.to_s}= #{eval(v.to_s,a)}"}.join ";"
puts "#{color_s}#{Time.new.strftime("%H:%M:%S")} line:#{line} -- #{s.to_s} -- #{vars}#{color_f}"
gets
end
a = 3
g = 5
puts "Hello World"
breakpoint "test",binding
f = 54
输出:
Hello World
22:58:40 line:13 -- test -- a= 3;g= 5;f=
您的“断点函数”是一个花哨的
put
,还是应该实际中断执行?为什么不使用pry
或debugger
来代替呢?添加了一个用于中断执行。什么变量名和值?问题已编辑。我希望函数breakpoint
打印调用者上下文中所有变量的名称和值,这里a=3
错误:eval]:无法将符号转换为字符串(TypeError)
b.instance\u eval{local_变量。每个{sym}放置“{sym}}}
打印函数breakpoint breakpoint中变量的名称