简体   繁体   中英

How to get current file and line number in Ruby?

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 '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.

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

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

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...

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

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

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

Edited so the output matches yours

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM