0

Is it possible to retrieve more than the file and the start line of the call stack in Ruby? Consider the following model file:

# sample.rb

def sample(a = nil, b = nil, c = nil, &block)
  yield if block_given?
  puts caller_locations
end

sample(
  1,
  2,
  3
)

sample do
  puts "lol"
end

When executed it outputs:

$ ruby sample.rb
sample.rb:8:in '<main>'
lol
sample.rb:14:in '<main>'

But what I want is this:

$ ruby sample.rb
sample.rb:8:0-12:1:in '<main>'
lol
sample.rb:14:0-16:3:in '<main>'

It would show me line number and column ranges. Can this be done with Ruby during runtime (not using Prism or alike)?

1
  • For yielding in Rails ERB partials I thought, found a trick to retrieve the line span of the block: <% line_span = yield.count("\n") + 1 %>, but this is all hacky and even wrong if the template block expanded to more HTML than there was ERB. Commented Aug 27 at 19:57

1 Answer 1

1

No, you can't get that level of detail directly from Ruby's runtime.

Think of your code file as a detailed blueprint. To run fast, Ruby reads the blueprint once and then only keeps "sticky notes" of where things start, which is what caller_locations gives you. It discards the full, detailed blueprint to save memory.

The only way to get the end line and column is to use a parser—like Ruby's official Prism library—to go back and re-read the original blueprint. Your script finds the "sticky note" location and then asks the parser to find the full dimensions for that spot on the map.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.