sawa sawa -4 years ago 69
Ruby Question

'respond_to?' versus 'defined?'

If I want to check whether a method with a given name is defined, which is better to use,

respond_to?
, or
defined?
?

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?

Answer Source

If I want to check whether a method with a given name is defined, which is better to use, respond_to?, or defined??

Neither. Use Module#method_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.

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download