开发者

How to get the name of the method in string format

I am calling Some_other_method开发者_StackOverflow中文版 inside Some_method. I want to pass the name Some_method to Some_other_method in string format. How can I do it? What should I put instead of question mark as a parameter?

def Some_method
  ...
  Some_other_method (?)
end


Use Kernel#__method__:

Returns the name of the current method as a Symbol. If called outside of a method, it returns nil.

For example:

def say_your_name
  puts __method__.to_s
end

You can leave off the to_s if you're happy with a symbol instead of a string.


You should use object#method for that. From the docs:

Looks up the named method as a receiver in obj, returning a Method object (or raising NameError). The Method object acts as a closure in obj‘s object instance, so instance variables and the value of self remain available.

> user = User.first        
=> #<User id: 1, email: "aslam@mapunity.in", created_at: "2011-05-24 07:17:51", updated_at: "2011-06-02 05:28:37", username: "admin"> 

> meth = user.method(:email)    
=> #<Method: User(#<Module:0x9ceff3c>)#_email> 

> meth.name    
=> :email 

> meth.name.to_s
=> "email" 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜