Milan Nosáľ Milan Nosáľ - 6 months ago 9
Ruby Question

How to find out from which line number the method was called in Ruby?

Let us have a following simple example:

def funny_function(param)
lineNumber = __LINE__ # this gives me the current line number
puts lineNumber
end


As we can see, I can get the current line number. However, my question is, is there a non-intrusive way to find out from which line number (and even a file) the method was called?

Non-intrusive meaning that I don't want the method user to know about that, she just has to provide the
param
parameter, e.g.:

funny_function 'Haha'


Maybe something like
caller.__LINE__
?

Answer

You can use caller_locations which has been added recently. It returns an array of Location objects. See http://ruby-doc.org/core-2.2.3/Thread/Backtrace/Location.html for details.

No need to parse the return of caller. Hooray.

Comments