如何在Ruby中获取当前文件和行号?

时间:2013-10-22 01:20:12

标签: ruby

我想实现这样的日志功能:

def mylog(str)
   puts __FILE__, ":"__LINENO__, ":", str  # Here how to get __FILE__ and __LINENO__ is my question.
end

当我致电mylog时:

mylog 'hello' # say I call this in my.rb line 10

我期待输出:

my.rb:10:hello

请帮助正确实施mylog功能。

3 个答案:

答案 0 :(得分:11)

使用caller是旧式的。相反,请使用caller_locations

def mylog(str)
  caller_locations(1, 1).first.tap{|loc| puts "#{loc.path}:#{loc.lineno}:#{str}"}
end

答案 1 :(得分:8)

您必须使用caller

def mylog(str)
  caller_line = caller.first.split(":")[1]
  puts "#{__FILE__} : #{caller_line} : #{str}"  
end

您可能想知道调用mylog的文件......

def mylog(str)
  caller_infos = caller.first.split(":")
  puts "#{caller_infos[0]} : #{caller_infos[1]} : #{str}"  
end

答案 2 :(得分:5)

获取行号的正确变量是__LINE__,因此您的函数的正确实现将是

def mylog(str)
 puts "#{__FILE__}:#{__LINE__}:#{str}"  
end

编辑所以输出与你的匹配