Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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__?

like image 996
Milan Nosáľ Avatar asked Oct 15 '25 16:10

Milan Nosáľ


2 Answers

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.

To add on to this caller_locations.first or caller_locations(0) gets the last method location, increment the parameter to pull specific steps.

like image 196
Pascal Avatar answered Oct 17 '25 12:10

Pascal


def b
  puts "world"
end

def a
  puts "hello"
end

p method(:a).source_location
=> ["filename.rb", 5]

Is this what your after?

like image 28
Ropeney Avatar answered Oct 17 '25 14:10

Ropeney



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!