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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With