0

Is there a way to obtain the string representation of fully qualified path to the method?

Consider following IRB session:

> foo = File.stat("/") > magic(foo.ctime) or foo.ctime.magic => "File::Stat#ctime" 

Is there any built-in function that does the "magic"? If not, can I get the string dynamically by doing some reflection?

note: I am aware of this question, but I can't use the pry.

1 Answer 1

3

One might call Object#method, returning an instance of Method:

foo.method(:ctime) #⇒ File::Stat#ctime() 

The fully qualified method name might be extracted e.g. from a Method#to_s:

foo.method(:ctime).to_s[/(?<=\A#<Method: ).*(?=>)\z/] #⇒ "File::Stat#ctime" 

I am not aware of any ability to get the fq-name directly from Method instance, without this regexp trick.

As properly pointed by Алексей Кузнецов in comments, to avoid regexp one might use:

full_method_name = "#{method.owner.name}##{method.name}" #⇒ "File::Stat#ctime" 
Sign up to request clarification or add additional context in comments.

2 Comments

@mudasobwa to build method full name without using regexp we could use method = foo.method(:ctime) # => File::Stat#ctime() full_method_name = "#{method.owner.name}##{method.name}" # => "File::Stat#ctime"
I figured there MUST be a better way than the regexp, and started down this path too -- but it looks like #name actually fails on built-in core methods implemented in C in this case? Maybe it's a bug? File.method(:ctime).owner.name # => nil. What?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.