让我们有以下简单的例子:
def funny_function(param)
lineNumber = __LINE__ # this gives me the current line number
puts lineNumber
end
正如我们所看到的,我可以得到当前的行号。不过,我的问题是,有没有办法找出从哪个行号(甚至一个文件)的方法称为非侵入性的方式?
我不希望用户的方法来了解有关非侵入式的意义,她只是必须提供param
参数,例如:
funny_function 'Haha'
也许像caller.__LINE__
?
您可以使用它是刚加入caller_locations
。它返回Location
对象的数组。见http://ruby-doc.org/core-2.2.3/Thread/Backtrace/Location.html了解详情。
不需要解析caller
的回报。万岁。
要添加到这个caller_locations.first
或caller_locations(0)
获得的最后一个方法的位置,增加了参数拉的具体步骤。
要获取AST函数调用caller[0].scan(/\d+/).first
线:
def func0
func1
end
def func1
func2
end
def func2
func3
end
def func3
p caller[0].scan(/\d+/).first
end
func0
def b
puts "world"
end
def a
puts "hello"
end
p method(:a).source_location
=> ["filename.rb", 5]
这是你的后?