如何找出在Ruby中调用了方法的行号?

How to find out from which line number the method was called in Ruby?

让我们举一个简单的例子:

def funny_function(param)
  lineNumber = __LINE__  # this gives me the current line number
  puts lineNumber
end

如我们所见,我可以获得当前行号。然而,我的问题是,有没有一种非侵入式的方法来找出调用方法的行号(甚至文件)?

非侵入性意味着我不想让方法用户知道,她只需要提供 param 参数,例如:

funny_function 'Haha'

也许是 caller.__LINE__

您可以使用最近添加的caller_locations。它 return 是 Location 个对象的数组。有关详细信息,请参阅 http://ruby-doc.org/core-2.2.3/Thread/Backtrace/Location.html

无需解析 caller 的 return。万岁。

要添加到此 caller_locations.firstcaller_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]

这是你想要的吗?