class Thread::Backtrace::Location
堆栈帧的对象表示,由 Kernel#caller_locations 初始化。
例如
# caller_locations.rb def a(skip) caller_locations(skip) end def b(skip) a(skip) end def c(skip) b(skip) end c(0..2).map do |call| puts call.to_s end
运行 ruby caller_locations.rb 将会产生
caller_locations.rb:2:in `a' caller_locations.rb:5:in `b' caller_locations.rb:8:in `c'
这里是另一个例子,结果略有不同
# foo.rb class Foo attr_accessor :locations def initialize(skip) @locations = caller_locations(skip) end end Foo.new(0..2).locations.map do |call| puts call.to_s end
现在运行 ruby foo.rb,您应该看到
init.rb:4:in `initialize' init.rb:8:in `new' init.rb:8:in `<main>'
公共实例方法
源代码
static VALUE
location_absolute_path_m(VALUE self)
{
return location_realpath(location_ptr(self));
}
返回此帧的完整文件路径。
与 path 相同,但即使帧位于主脚本中,也会返回绝对路径。
源代码
static VALUE
location_base_label_m(VALUE self)
{
return location_base_label(location_ptr(self));
}
返回此帧的基本标签,通常等于标签,不带修饰。
考虑以下示例
def foo puts caller_locations(0).first.base_label 1.times do puts caller_locations(0).first.base_label 1.times do puts caller_locations(0).first.base_label end end end
调用 foo 的结果如下
foo foo foo
源代码
static VALUE
location_inspect_m(VALUE self)
{
return rb_str_inspect(location_to_str(location_ptr(self)));
}
返回与在 to_str 的字符串表示形式上调用 inspect 相同的结果。
源代码
static VALUE
location_label_m(VALUE self)
{
return location_label(location_ptr(self));
}
返回此帧的标签。
通常由方法、类、模块等名称组成,带有修饰。
考虑以下示例
def foo puts caller_locations(0).first.label 1.times do puts caller_locations(0).first.label 1.times do puts caller_locations(0).first.label end end end
调用 foo 的结果如下
foo block in foo block (2 levels) in foo
源代码
static VALUE
location_lineno_m(VALUE self)
{
return INT2FIX(location_lineno(location_ptr(self)));
}
返回此帧的行号。
例如,使用 Thread::Backtrace::Location 中的 caller_locations.rb
loc = c(0..1).first loc.lineno #=> 2
源代码
static VALUE
location_path_m(VALUE self)
{
const rb_iseq_t *iseq = location_iseq(location_ptr(self));
return iseq ? rb_iseq_path(iseq) : Qnil;
}
返回此帧的文件名。这通常是一个绝对路径,除非帧位于主脚本中,在这种情况下,它将是在命令行上传递的脚本位置。
例如,使用 Thread::Backtrace::Location 中的 caller_locations.rb
loc = c(0..1).first loc.path #=> caller_locations.rb
源代码
static VALUE
location_to_str_m(VALUE self)
{
return location_to_str(location_ptr(self));
}
返回一个 Kernel#caller 样式的字符串,表示此帧。