字符串中的引用方法名称
Reference method name in string
可以这样做:
s="puts"
send(s,"Hello World!")
# => Hello World!
如何检查 s
是否是一种方法?如果是:
s="nomethod"
send(s,arg)
会失败。
这会很酷:
ismethod? s
P.S。我正在从 PHP 移植一些东西,它依赖于:
if (function_exists($s))
...
要是Ruby有这么简单的东西就好了。
试试这个:
respond_to?(method_name)
如果当前对象(自身)响应该名称的方法,它应该 return 为真。您可以在任何 Ruby 对象上使用 respond_to?
。
可以这样做:
s="puts"
send(s,"Hello World!")
# => Hello World!
如何检查 s
是否是一种方法?如果是:
s="nomethod"
send(s,arg)
会失败。
这会很酷:
ismethod? s
P.S。我正在从 PHP 移植一些东西,它依赖于:
if (function_exists($s))
...
要是Ruby有这么简单的东西就好了。
试试这个:
respond_to?(method_name)
如果当前对象(自身)响应该名称的方法,它应该 return 为真。您可以在任何 Ruby 对象上使用 respond_to?
。