如何找出从中行号方法被调用在Ruby中?

问题描述 投票:2回答:3

让我们有以下简单的例子:

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

正如我们所看到的,我可以得到当前的行号。不过,我的问题是,有没有办法找出从哪个行号(甚至一个文件)的方法称为非侵入性的方式?

我不希望用户的方法来了解有关非侵入式的意义,她只是必须提供param参数,例如:

funny_function 'Haha'

也许像caller.__LINE__

ruby metaprogramming
3个回答
4
投票

您可以使用它是刚加入caller_locations。它返回Location对象的数组。见http://ruby-doc.org/core-2.2.3/Thread/Backtrace/Location.html了解详情。

不需要解析caller的回报。万岁。

要添加到这个caller_locations.firstcaller_locations(0)获得的最后一个方法的位置,增加了参数拉的具体步骤。


1
投票

要获取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

1
投票
def b
  puts "world"
end

def a
  puts "hello"
end

p method(:a).source_location
=> ["filename.rb", 5]

这是你的后?

© www.soinside.com 2019 - 2024. All rights reserved.