Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current file and line number in Ruby?

Tags:

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.

like image 472
TieDad Avatar asked Oct 22 '13 01:10

TieDad


2 Answers

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

like image 68
Teddy Avatar answered Oct 05 '22 12:10

Teddy


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
like image 33
gmalette Avatar answered Oct 05 '22 12:10

gmalette