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

时间:2021-04-28 07:29:22

I want to implement a log function like this:

我想实现这样的日志函数:

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

When I call mylog:

当我打电话给mylog:

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

I expect output:

我期待输出:

my.rb:10:hello

Please help give right implementation of mylog function.

请帮助正确实现mylog功能。

3 个解决方案

#1


5  

You'll have to use caller

你必须使用来电者

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

You'll probably want to know the file from which mylog was called too...

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

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

#2


11  

Using caller is old-style. Rather, use caller_locations.

使用调用者是旧式的。相反,使用caller_locations。

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

#3


5  

The correct variable to get line number is __LINE__, so the proper implementation of your function would be

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

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

Edited so the output matches yours

编辑所以输出与你的匹配

#1


5  

You'll have to use caller

你必须使用来电者

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

You'll probably want to know the file from which mylog was called too...

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

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

#2


11  

Using caller is old-style. Rather, use caller_locations.

使用调用者是旧式的。相反,使用caller_locations。

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

#3


5  

The correct variable to get line number is __LINE__, so the proper implementation of your function would be

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

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

Edited so the output matches yours

编辑所以输出与你的匹配