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

Tie*_*Dad 10 ruby

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

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

我打电话的时候mylog:

mylog 'hello' # say I call this in my.rb line 10
Run Code Online (Sandbox Code Playgroud)

我期待输出:

my.rb:10:hello
Run Code Online (Sandbox Code Playgroud)

请帮助正确实现mylog功能.

saw*_*awa 12

使用caller是旧式的.相反,使用caller_locations.

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


gma*_*tte 9

你必须使用 caller

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

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

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


Ted*_*ddy 5

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

def mylog(str)
 puts "#{__FILE__}:#{__LINE__}:#{str}"  
end
Run Code Online (Sandbox Code Playgroud)

编辑,以便输出与你的匹配