我在Some_method
内调用Some_other_method
。我想以字符串格式将名称Some_method
传递给Some_other_method
。我该怎么做?我应该把什么,而不是问号作为参数?如何获取字符串格式的方法名称
def Some_method
...
Some_other_method (?)
end
我在Some_method
内调用Some_other_method
。我想以字符串格式将名称Some_method
传递给Some_other_method
。我该怎么做?我应该把什么,而不是问号作为参数?如何获取字符串格式的方法名称
def Some_method
...
Some_other_method (?)
end
您应该使用object#method。从文档:
在obj中查找指定的方法作为接收方,返回一个Method对象(或引发NameError)。 Method对象充当obj对象实例中的闭包,所以实例变量和self值保持可用。
> user = User.first
=> #<User id: 1, email: "[email protected]", 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"
返回当前方法作为符号的名称。如果在方法外调用,则返回nil。
例如:
def say_your_name
puts __method__.to_s
end
可以去掉的to_s
如果你满意的一个符号,而不是一个字符串。
这与要求的内容相反。问题是要求将方法更改为字符串。您正在使用符号/字符串作为方法。 – sawa 2011-06-15 07:43:43
对。我同意。更新了答案以反映更改。 – 2011-06-15 08:05:07