[英]How to get current file and line number in 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
功能。
使用caller
是舊式的。 相反,使用caller_locations
。
def mylog(str)
caller_locations(1, 1).first.tap{|loc| puts "#{loc.path}:#{loc.lineno}:#{str}"}
end
你必須使用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
獲取行號的正確變量是__LINE__
,因此您的函數的正確實現將是
def mylog(str)
puts "#{__FILE__}:#{__LINE__}:#{str}"
end
編輯,以便輸出與你的匹配
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.