问题描述
如果要检查是否定义了具有给定名称的方法,最好使用respond_to?
或defined?
?
If I want to check whether a method with a given name is defined, which is better to use, respond_to?
, or defined?
?
从效率的角度来看,可以使用defined?
作为参数,因为defined?
是内置关键字,而respond_to?
是一种方法,因此前者可能会更快.但是另一方面,在已知要检查的表达式是一种简单方法的情况下,defined?
需要解析整个表达式,与使用respond_to?
相比,这可能是一个缺点.接受参数作为方法名称.
From the point of view of efficiency, there can be an argument for using defined?
because defined?
is a built in keyword, whereas respond_to?
is a method, and hence the former might be faster. But on the other hand, under the situation that the expression to be checked is known to be a simple method, defined?
needs to parse the whole expression, and that may be a drawback as compared to using respond_to?
, which just needs to accept the argument as a method name.
哪个更好?除了效率之外,还有其他要考虑的地方吗?
Which is better? Are there points other than efficiency that should be considered?
推荐答案
都不是.使用 Module#method_defined?
Neither. Use Module#method_defined?
这并不是使用更好"的问题: Object#respond_to?
方法或defined?
一元前缀运算符(尽管有名称!)检查方法是否已定义:它们都检查是否接收者响应一个消息,这是完全不同的事情.
It's not really a question which is "better" to use: neither the Object#respond_to?
method nor the defined?
unary prefix operator (despite the name!) checks whether the method is defined: they both check whether the receiver responds to a message, which is a completely different thing.
只有Module#method_defined?
会实际检查该方法是否已定义:
Only Module#method_defined?
will actually check whether the method is defined:
class Foo
def method_missing(*) end
def respond_to_missing?(*) true end
end
foo = Foo.new
defined? foo.bar
#=> 'method'
foo.respond_to?(:bar)
#=> true
Foo.method_defined?(:bar)
#=> false
这篇关于'回应?'与“已定义?"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!