加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 04:39:47 所属栏目:百科 来源:网络整理
导读:我想实现这样的日志函数: 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 请帮
我想实现这样的日志函数:
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功能.

解决方法

你必须使用来电者
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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读