2

我在Some_other_method里面打电话Some_method。我想以字符串格式传递Some_method名称Some_other_method。我该怎么做?我应该把什么代替问号作为参数?

def Some_method
  ...
  Some_other_method (?)
end
4

2 回答 2

4

使用Kernel#__method__

以符号的形式返回当前方法的名称。如果在方法外调用,则返回 nil。

例如:

def say_your_name
  puts __method__.to_s
end

to_s如果您对符号而不是字符串感到满意,则可以省略。

于 2011-06-15T07:08:11.050 回答
2

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" 
于 2011-06-15T06:58:28.720 回答