def test_method
result = []
result << yield # How to get the line number of where next was invoked in this block
puts caller[0] # Gives the line number of another_method
result
end
def another_method
a = 1
b = 2
test_method do
next if a == 1
next if b == 200
end
end
In the above code, yield returns at next if a == 1, how to get the line number of source code where next was invoked in the given block from the test_method?
For debugging purposes, you can use TracePoint to monitor the executed lines:
# test.rb # 1
# 2
def test_method # 3
result = [] # 4
trace = TracePoint.new(:line) do |tp| # 5
p tp # 6
end # 7
trace.enable do # 8
result << yield # 9
end # 10
result # 11
end # 12
# 13
def another_method # 14
a = 1 # 15
b = 2 # 16
test_method do # 17
next if a == 1 # 18
next if b == 200 # 19
end # 20
end # 21
# 22
another_method # 23
Output:
#<TracePoint:line@test.rb:9 in `test_method'>
#<TracePoint:line@test.rb:18 in `another_method'>