Object#caller and Exception#backtrace

Seeing the wonderfulness of the 'to_ruby' method I mentioned just recently got me thinking about Object#caller and Exception#backtrace again.

I don't know about anybody else, but it seems strange to me that these potentially really useful methods return an array of fixed strings. I'm also puzzled by what information it is they return, and what they don't:

["exception.rb:84:in `start_juggernaut'",
  "exception.rb:77:in `initialize'",
  "exception.rb:108:in `new'",
  "exception.rb:108"]

They return the filename and a line number, which is great. A method, which is useful... but no class / module or other form of nesting? Does anybody understand why that is? Is there any desire to fix it? I think having the class/module, at least, would be hella-useful.

For my own sake, I've created a little bit of ruby code that defines a couple of methods for Object (caller_as_arrays and caller_as_objects) and for Exception (backtrace_as_arrays and backtrace_as_objects).

caller_as_arrays and backtrace_as_arrays return something like:

[["caller.rb", 84, "start_juggernaut"],
  ["caller.rb", 77, "initialize"],
  ["caller.rb", 106, "new"],
  ["caller.rb", 106]]

caller_as_objects and backtrace_as_objects return something like:

[#<Caller:0x402e6ccc
   @filename="caller.rb",
   @line_no=101,
   @method_name="feets_dont_fail_me_now">,
  #<Caller:0x402e6cb8
   @filename="caller.rb",
   @line_no=84,
   @method_name="start_juggernaut">,
  #<Caller:0x402e6ca4
   @filename="caller.rb",
   @line_no=77,
   @method_name="initialize">,
  #<Caller:0x402e6c90 @filename="caller.rb", @line_no=106, @method_name="new">,
  #<Caller:0x402e69d4 @filename="caller.rb", @line_no=106, @method_name=nil>]

Would anybody find this useful? Any comments on the names of the methods or objects? Shall I upload to rubyforge and figure out how to gemificate?

Ben

Ben Giddings wrote:

Seeing the wonderfulness of the 'to_ruby' method I mentioned just recently got me thinking about Object#caller and Exception#backtrace again.

I don't know about anybody else, but it seems strange to me that these potentially really useful methods return an array of fixed strings. I'm also puzzled by what information it is they return, and what they don't:

["exception.rb:84:in `start_juggernaut'",
"exception.rb:77:in `initialize'",
"exception.rb:108:in `new'",
"exception.rb:108"]

They return the filename and a line number, which is great. A method, which is useful... but no class / module or other form of nesting? Does anybody understand why that is? Is there any desire to fix it? I think having the class/module, at least, would be hella-useful.

You can use Binding.of_caller to get the binding of your last-most caller. Using that you can also get the class and instance of it. It's quite limited, but IMHO still useful.

binding_of_caller.rb (2.81 KB)