Position of the method in source file

144 views Asked by At

When I try to extract the position of a method in the source code, I can do:

class Object  
    def source_position
        puts caller.first  
    end  
end  

so that when I use it in a chain that is located on the n-th line of a source code, it gives me the desired result:

test.rb

.
.
n:   'abcde'.source_position
.
.

# => test.rb:n:in `<main>`

but when I make a line break before this command, it gives back the position of the beginning of the chain instead of the position of the method in question:

.
.
n:    'abcde'.
n+1:  source_position
.
.

# => test.rb:n:in `<main>`

or (in ruby 1.9),

.
.
n:    'abcde'
n+1:  .source_position
.
.

# => test.rb:n:in `<main>`

Is this a feature instead of a bug? If so, is there a way to get the position of the method, so that in the last two examples above, n+1 will be returned as the line instead of n?

2

There are 2 answers

0
robustus On

´source_position´ is an instance_methods and therefore operates on the called object. As your code puts the line the caller(the object) is located in, this is not only a feature but exactly what you coded.

In short, ´source_position` doesn't retrieve the position of the method in your code, but the position of the object it is called on.

1
nhed On

Not a ruby expert but sounds like a reasonable thing for ruby to do ...

That having been said, will puts __LINE__ work for you?

I can't tell because you really didn't say why you need or how you will use it